Converting object returned from Linq.Dynamic

c# dynamic dynamic-linq entity-framework linq

Question

I am using the Linq.Dynamic Library and EF6. I am attempting to select only the fields from a database that my user selects.

However, all that is returned is a List<object>, I have attempted to Cast<dynamic>, and every way I can think of, but no matter what the object has 0 fields.

I have also tried explicitly declaring as an IEnumerable and that too was unsuccessful, and was unable to call .ToList(), without first calling Cast<T> which too was unsuccessful.

When converting one of the objects to string I get: "{filenumber=345400, custom2=, custom3=, custom6=4076995332, custom8=4072121417}".

The data is being returned I simply cannot cast it to the appropriate type.

var query = cmax.dbases
    .Where(w => statuses.Any(a => w.statusname == a) && portfolios.Any(a => w.portfolio == a))
    .Select(string.Format("new ({0})", string.Join(",", fields)))
    .Take(Math.Min((int) takeAmount, count - taken));

var take = await query.ToListAsync();

take.ForEach(data => {
    var type = take.GetType();
    var properties = type.GetProperties();
    var propCount = properties.Count();
    properties.ToList().ForEach(prop => {
        var name = prop.Name;
    });
});
1
2
4/29/2015 6:06:29 PM

Popular Answer

In one of my use cases I have converted the results to List<string[]> through an extension for IQueryable. As I know my column order in Select("New (columnNames...) "), I could easily figure out which one is which.

so here is the code of the extension

public static IList<string[]> ToStringArray(this IQueryable queryFinal)
{
  var query = (IQueryable<dynamic>)queryFinal;
  IList<dynamic> data = query.ToList();
  System.Reflection.PropertyInfo[] props = null;
  if (data.Count > 0) props = data[0].GetType().GetProperties();
  if (props == null) return new List<string[]>();
  /*I do other things using reflection here*/
  return data.Select(d => props.Select(p => (p.GetValue(d, null) ?? string.Empty).ToString()).OfType<string>().ToArray()).ToList();
}

use it as

var result = query.ToStringArray();
1
4/29/2015 8:09:19 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow