1

System.Linq.Dynamicと共に EntityFramework を使用しており、次のように Employee POCO クラスを定義しました。

public class Employee
{
    public long Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Company Company { get; set; }
    public Country Country { get; set; }
}


このコードを使用して、国名で GroupBy を実行しています。

var query = Employees.Include(e => e.Company).Include(e => e.Country);  
var groupByQuery = query.GroupBy("new (Country.Code as GroupByField)", "new (it AS XEmployee, it.Company AS XCompany, it.Country AS XCountry)");
var selectQuery = groupByQuery.Select("new (Key.GroupByField, it as Grouping)");
var grouping = selectQuery.Select("it.Grouping") as IQueryable<IGrouping<DynamicClass, DynamicClass>>;
var objects = grouping.First().AsQueryable() as IQueryable<object>;

// This line gives me : ParseException: No property or field 'XEmployee' exists in type 'DynamicClass'
var employees = objects.Select("it.XEmployee");

DynamicClass からすべてのプロパティをダンプすると、XEmployee が有効なパブリック プロパティになるため、非常に奇妙です。

var firstObject = objects.First();
firstObject.GetType().GetProperties().Dump();

ショー ここに画像の説明を入力

4

1 に答える 1

0

オブジェクトからプロパティを取得し、これを必要な型にキャストする拡張メソッドを作成しました。

拡張メソッド「Select」については、このコードを参照してください

public static class DynamicQueryableExtensions
{
   public static IEnumerable<TEntity> Select<TEntity>(this IEnumerable<object> source, string propertyName)
   {
       return source.Select(x => GetPropertyValue<TEntity>(x, propertyName));
   }

   private static T GetPropertyValue<T>(object self, string propertyName)
   {
       var type = self.GetType();
       var propInfo = type.GetProperty(propertyName);

       try
       {
           return propInfo != null ? (T)propInfo.GetValue(self, null) : default(T);
       }
       catch
       {
           return default(T);
       }
   }
}

コードは次のように使用されます。

// This line will just work fine.
var employees = objects.Select<Employee>("XEmployee");
employees.Dump();


実際の例については、github にある私のKendoGridBinderExプロジェクトを参照してください。

于 2013-04-09T10:41:47.453 に答える