简体   繁体   English

我可以在 Entity Framework Code First 中使用来自我的域模型的谓词吗?

[英]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:你有几个选择:

  • Rephrase the query to use standard operations, eg smaller-than.重新表述查询以使用标准操作,例如小于。 This will duplicate the logic from the predicate, though.不过,这将复制谓词中的逻辑。
  • Use a raw SQL query.使用原始 SQL 查询。 This will also duplicate the logic, but in SQL.这也将复制逻辑,但在 SQL 中。
  • Load the entire list of entities and then filter in-memory (ie 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.

相关问题 如何从Entity Framework 4.3代码优先模型生成DDL脚本? - How can I generate DDL scripts from Entity Framework 4.3 Code-First Model? 实体框架DB-First - 我可以从基础模型继承以添加我的功能吗? - Entity Framework DB-First - can I inherit from base model in order to add my functionality? 我可以将Hangfire与现有的实体框架代码优先应用程序一起使用吗? - Can I use Hangfire with an existing entity framework code first application? 首先从实体框架模型切换到代码 - Switching from entity framework model first to code first 首先使用实体​​框架模型进行域驱动设计 - Domain Driven Design with Entity Framework Model First 实体框架代码优先迁移添加了我的模型中不存在的字段 - Entity Framework Code First migrations adds a field not present in my model 实体框架代码优先:如何为这个简单的引用场景建模? - Entity Framework Code First: How can I model this simple referral scenario? 数据库设计中的实体框架代码优先模型 - Entity Framework Code First model from Database design 为什么不能使用Entity Framework Code First将新数据添加到数据库中? - Why can't I add new data to my database with Entity Framework Code First? 当我已经有了我的模型和数据库时,我可以使用实体框架吗? - Can I use the Entity Framework when I already have my Model and database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM