Linq 如何为实体框架创建存储表达式?
假设我有这样的疑问Linq 如何为实体框架创建存储表达式?,linq,entity-framework-5,Linq,Entity Framework 5,假设我有这样的疑问 context.MyClass.ListSubClasses.Sum(x=> x.UseNetPrice ? x.NetPrice : x.TotalPrice); 这只是一个例子,我的lamda表达式要复杂得多,我在几个地方使用它。 我想做的是 context.MyClass.ListSubCalsses.Sum(x=>x.Price()); 我的方法是: public static double? Price(IQueryable<MyClass&g
context.MyClass.ListSubClasses.Sum(x=> x.UseNetPrice ? x.NetPrice : x.TotalPrice);
这只是一个例子,我的lamda表达式要复杂得多,我在几个地方使用它。
我想做的是
context.MyClass.ListSubCalsses.Sum(x=>x.Price());
我的方法是:
public static double? Price(IQueryable<MyClass> class)
{ return class.Select(x=> x.UseNetPrice ? x.NetPrice : x.TotalPrice);}
publicstaticdouble?价格(IQueryable类)
{返回类。选择(x=>x.UseNetPrice?x.NetPrice:x.TotalPrice);}
我犯了一个错误。
您可以帮我举一个如何编写存储表达式的示例吗?您可以使用在助手方法中创建完整的lambda表达式,然后重新运行表达式
那么,你要:
context.YourEntities.Where(HelperClass.GetPricePredicate());
您的GetPricePredicate()
可以是以下内容:
public Expression<Func<YourEntity, bool>> GetPricePredicate()
{
var myPredicate = PredicateBuilder.True<YourEntity>();
myPredicate = myPredicate.And(y => y.idTenant == tenantID);
myPredicate = myPredicate.And(y => y.idCategory == 1);
return myPredicate;
}
GetPricePredicate()公共表达式
{
var myPredicate=PredicateBuilder.True();
myPredicate=myPredicate.And(y=>y.idTenant==tenantID);
myPredicate=myPredicate.And(y=>y.idCategory==1);
返回myPredicate;
}
谢谢,但是计算要复杂得多,它应该返回double而不是bool。因此,您可以接收项目列表作为参数并进行计算,而不是只返回表达式(此方法只返回表达式,然后使用并执行查询)。。。用一种方法做这件复杂的事情,并在需要时随时使用它。但是不要弄乱lambda中的表达式和扩展。。。它很快就会变得复杂。