[英]Can I use predicates from my Domain Model in Entity Framework Code First?
I've got a class with a bool
method, eg:我有一个带有bool
方法的类,例如:
public bool IsInFuture()
{ return this.Date > DateTime.Now; }
And I store it in a database using EF Code First.我使用 EF Code First 将其存储在数据库中。 If I'll try to use that predicate in Linq operations, I'll get an exception, as it can not be translated into SQL:如果我尝试在 Linq 操作中使用该谓词,我会得到一个异常,因为它无法转换为 SQL:
await context.Where(order => order.IsInFuture()).ToListAsync();
That predicate's logic can be rather complicated and I wouldn't like to duplicate it in my code.该谓词的逻辑可能相当复杂,我不想在我的代码中复制它。 It there any way I can "inline" it's code into Linq operations?有什么办法可以将它的代码“内联”到 Linq 操作中? I'm pretty sure, this problem has a solution.我很确定,这个问题有解决方案。
Thanks in advance!提前致谢!
You can't use the predicate directly.您不能直接使用谓词。 How should EF know how to convert it into an SQL WHERE statement? EF 应该如何知道如何将其转换为 SQL WHERE 语句?
You have a few alternatives:你有几个选择:
Where()
after ToList()
).加载整个实体列表,然后在内存中过滤(即Where()
ToList()
之后的Where()
ToList()
)。 Like this, you can reuse the predicate.像这样,您可以重用谓词。 Note that this only a good idea for very small data sets.请注意,这仅适用于非常小的数据集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.