저는 결과를 얻기 위해 값 사전을 얻으려면 속성 목록을 지정하기 위해 Entity Framework의 동적 투영을 구현하려고합니다. 런타임시EF 동적 투영 (속성 - 값 쌍 사전에 매핑)
public static IQueryable<Dictionary<string, object>> ProjectionMap<TSource>
(IQueryable<TSource> sourceModel, IEnumerable<string> properties)
{
var itemParam = Expression.Parameter(typeof (TSource), "item");
var addMethod = typeof (Dictionary<string, object>).GetMethod("Add");
var elements = properties.
Select(
property =>
Expression.ElementInit(addMethod, Expression.Constant(property),
GetPropertyExpression<TSource>(itemParam, property))).
ToList();
var newDictionaryExpression =
Expression.New(typeof (Dictionary<string, object>));
var dictionaryInit = Expression.ListInit(newDictionaryExpression, elements);
var projection = Expression.Lambda<Func<TSource, Dictionary<string, object>>>(dictionaryInit, itemParam);
return sourceModel.Select(projection);
}
public static Expression GetPropertyExpression<T>(ParameterExpression parameter, string propertyName)
{
var properties = typeof (T).GetProperties();
var property = properties.First(p => p.Name == propertyName);
return Expression.Property(parameter, property);
}
다음 코드 인상 예외에게 하나의 요소
var query = ProjectionMap(db.Posts, new[]{"Subject"});
var result = query.ToList();
NotSupportedException이 만 목록 초기화 항목을 실행하는 엔티티에 LINQ에서 지원됩니다.
코드를 수정하거나 제안 사항을 올바르게 구현하는 방법에 대한 아이디어가 있으십니까? 미리 감사드립니다.