我所拥有的是以下方法。我使用匿名投影来过滤包含EF的内容。我从这篇博文中学到了这个方法: http://thedatafarm.com/data-access/use-projections-and-a-repository-to-fake-a-filtered-eager-load/
public IEnumerable<Entities.Nutrient> FindAllForSpecificLanguage(bool overridePossibleLogicalDelete)
{
using (var context = CreateObjectContext())
{
context.ContextOptions.LazyLoadingEnabled = false;
Entities.Nutrient[] result;
var list = context.Nutrients
.Select(nut => new
{
Entity = nut,
Descriptions = nut.Descriptions.Where(desc => desc.LanguageCode.Equals(DataLanguageContext.Current.DataLanguageCode))
}).ToList(); //perform query
var resultList = list
.Select(entity => entity.Entity);
return resultList;
}
}
这个方法应该内置到所有服务中(api支持大约30种语言,目前我们有很多数据库开销......)。 我试图以通用的方式构建它,但我对表达树的经验非常可怜。我以为我完全重新创建了这个功能,但我错过了一些东西,因为它不起作用。 这就是我到目前为止所做的:
public virtual IEnumerable<TEntity> FindAllForSpecificLanguage(bool overridePossibleLogicalDelete, Expression<Func<TEntity, IEnumerable<object>>> selectEntityDescriptions)
{
using (var context = CreateObjectContext())
{
context.ContextOptions.LazyLoadingEnabled = false;
ObjectQuery<TEntity> queryObjectSet = GetObjectSet(context);
TEntity[] result;
Type anonType = new {Entity = default(TEntity), Descriptions = Enumerable.Empty<object>()}.GetType();
// (entityManagerBaseEntity) => new { Entity = entityManagerBaseEntity, Descriptions = selectEntityDescriptions(entityManagerBaseEntity) }
// 1) "(entityManagerBaseEntity) =>"
var pe = Expression.Parameter(typeof(TEntity), "entityManagerBaseEntity");
// 2) "selectEntityDescriptions(entityManagerBaseEntity)"
var exprFunc = Expression.Invoke(selectEntityDescriptions, pe);
// get constructor for anonymous type
var constructorInfo = anonType.GetConstructor(new[] { typeof(TEntity), typeof(IEnumerable<object>) });
// 3) "new AnonType(entityManagerBaseEntity, exprFunc(entityManagerBaseEntity))"
var constructAnonType = Expression.New(constructorInfo, pe, exprFunc);
// 4) combine all to a lambda
// {entity => new <>f__AnonymousType0`2(entity, Invoke(entity => entity.Descriptions.Where(desc => desc.LanguageCode.Equals(DataLanguageContext.Current.DataLanguageCode)), entity))}
var cooleExpression = Expression.Lambda<Func<TEntity, dynamic>>(constructAnonType, pe);
//var bla = cooleExpression.Compile();
//var list = queryObjectSet.AsQueryable().Provider.CreateQuery<dynamic>(cooleExpression).ToList();
var list = queryObjectSet.Select(cooleExpression).ToList(); //perform query
var resultList = list
.Select(entity => entity.Entity as TEntity);
return resultList;
}
}
(注意:CreateObjectContext和GetObjectSet是完美的工作方法)
应该这样称呼:
_nutrientManager.FindAllForSpecificLanguage(true, (entity) => entity.Descriptions.Where(desc => desc.LanguageCode.Equals(DataLanguageContext.Current.DataLanguageCode)))
构建的表达式在注释中输入。我觉得它看起来很好,但从未执行过连接。 如果我调试我得到以下stacktrace:
System.NotSupportedException:LINQ to Entities中仅支持无参数构造函数和初始值设定项。 at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.NewTranslator.TypedTranslate(ExpressionConverter parent,NewExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent,Expression linq)
答案 0 :(得分:1)
所以..一些事情:
整个解决方案可以在这里找到: https://github.com/YoeriVD/entity-framework-filter-on-include/blob/master/ExpressionTrees/Program.cs
重要的是:
private static void Main(string[] args)
{
FilterOnInclude<Car, Wheel>(car => car.Wheels, wheel => wheel.SizeInInches == 14)
.ForEach(car => Console.WriteLine($"car : {car.Name} wheels: {car.Wheels.Count}"));
}
private static IEnumerable<TEntity> FilterOnInclude<TEntity, TChildEntity>(
Expression<Func<TEntity, IEnumerable<TChildEntity>>> propertyExpression,
Expression<Func<TChildEntity, bool>> predicateExpression)
where TEntity : class
{
using (var context = new CarContext())
{
context.Configuration.LazyLoadingEnabled = false;
var selector = CreateSelector(propertyExpression, predicateExpression);
return
context.Set<TEntity>().Select(
selector
).ToList().Select(e => e.Entity).ToArray();
}
}
private static Expression<Func<TEntity, EntityWithFilteredChildren<TEntity, TChildEntity>>> CreateSelector
<TEntity, TChildEntity>(
Expression<Func<TEntity, IEnumerable<TChildEntity>>> propertyExpression,
Expression<Func<TChildEntity, bool>> predicateExpression)
{
var selectType = typeof (EntityWithFilteredChildren<TEntity, TChildEntity>);
//bind entity
var entityValueParam = Expression.Parameter(typeof (TEntity), "entityValue");
var entityProp = selectType.GetProperty("Entity");
var entityValueAssignment = Expression.Bind(
entityProp, entityValueParam);
//bind collection
var childrenProp = selectType.GetProperty("Children");
var descriptionsMemberExpression = (propertyExpression.Body as MemberExpression);
var descriptionsPropertyInfo = (PropertyInfo) descriptionsMemberExpression.Member;
var descriptionsProperty = Expression.Property(entityValueParam, descriptionsPropertyInfo);
//perform where call
var whereCall = Expression.Call(typeof (Enumerable), "Where", new[] {typeof (TChildEntity)}, descriptionsProperty,
predicateExpression);
var descriptionValueAssignment = Expression.Bind(
childrenProp, whereCall);
var ctor = Expression.New(selectType);
var memberInit = Expression.MemberInit(ctor, entityValueAssignment, descriptionValueAssignment);
var selector = Expression.Lambda<Func<TEntity, EntityWithFilteredChildren<TEntity, TChildEntity>>>(memberInit,
entityValueParam);
return selector;
}
public class EntityWithFilteredChildren<T, TChild>
{
public T Entity { get; set; }
public IEnumerable<TChild> Children { get; set; }
}
答案 1 :(得分:0)
显然,我不知道您项目的更大结构,但是您可以通过将Entities.Nutrient
替换为TEntity
来使您的第一个示例更通用吗?这是我正在考虑的事情:
public IEnumerable<TEntity> FindAllForSpecificLanguage<TEntity>(
Func<DbContext, IEnumerable<TEntity>> selectEntities,
Func<TEntity, IEnumerable<object>> selectEntityDescriptions)
{
using (var context = CreateObjectContext())
{
context.ContextOptions.LazyLoadingEnabled = false;
var list = selectEntities(context)
.Select(nut => new
{
Entity = nut,
Descriptions = selectEntityDescriptions
}).ToList(); //perform query
var resultList = list
.Select(entity => entity.Entity);
return resultList;
}
}