[英]Using dynamic linq in EF Linq to Entities
I'm building up a Linq.Expressions.Expression at runtime and then I thought I would use it like so: 我正在运行时建立一个Linq.Expressions.Expression,然后我想我会这样使用它:
Type myTypeVariable = viewModel.typeVariable;
DbContext db = //get entity model for myTypeVariable
Expression myExpression = //build a predicate of myTypeVariable from viewModel
var query = (IQueryable<myType>)db.Set(myTypeVariable);
var results = query.Provider.CreateQuery(myExpression);
The error I'm getting is at the .CreateQuery()
stage: "Linq to Entities query expresions can only be constructed from instances that implement the IQueryable interface." 我遇到的错误是在
.CreateQuery()
阶段:“只能从实现IQueryable接口的实例构造Linq to Entities查询.CreateQuery()
。” My confusion comes from the fact that if the last line it replaced with this I get results?: results = query.Where(c=>c.ID>0).ToList();
我的困惑来自这样一个事实,即如果最后一行替换为该行,我会得到结果?:
results = query.Where(c=>c.ID>0).ToList();
I've mostly been following this: https://msdn.microsoft.com/en-us/library/bb882637.aspx 我主要关注以下内容: https : //msdn.microsoft.com/zh-cn/library/bb882637.aspx
How do I get results from my DbSet using my Expression predicate? 如何使用Expression谓词从DbSet中获得结果?
Usually building expression trees is the hard part. 通常,构建表达式树是困难的部分。 See Building expression trees for more details.
有关更多详细信息,请参见构建表达式树 。
The are tools and libraries out there to help. 有工具和库可以为您提供帮助。 The use fascades or tools to help build expressions.
使用外观或工具来帮助构建表达式。 eg Predicate Builder
例如谓词生成器
You can pass the expression to a generic repository to do dynamic Linq in EF. 您可以将表达式传递到通用存储库,以在EF中执行动态Linq。 For example:
例如:
public virtual IQueryable<TPoco> GetList(Expression<Func<TPoco, bool>> predicate) {
return Context.Set<TPoco>().Where(predicate);
}
// a small sample building an expression for Contains string
public static Expression<Func<TPoco, bool>> GetContainsPredicate<TPoco>(string propertyName, string containsValue)
{
// (tpoco t) => t.propertyName.Contains(value ) as expression
var parameterExp = Expression.Parameter(typeof(TPoco), @"t");
var propertyExp = Expression.Property(parameterExp, propertyName);
MethodInfo method = typeof(string).GetMethod(@"Contains", new[] { typeof(string) });
var someValue = Expression.Constant(containsValue, typeof(string));
var containsMethodExp = Expression.Call(propertyExp, method, someValue);
return Expression.Lambda<Func<TPoco, bool>>(containsMethodExp, parameterExp);
}
USAGE: 用法:
var someExp = MyTool.GetContainsPredicate("FIELDNAME","SomeString");
var resultQueryable = myRepOfTpoco.GetList(someExp ) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.