EF 扩展功能

发布于 2024-12-18 12:56:20 字数 386 浏览 3 评论 0原文

我打算在同一个项目中使用 Linq to sql 和 EF 4.x(出于某种原因),

但是 EF 中有一些东西,IMO 是这样的“奇怪”:

db.SomeTable.Where(x => x.Date > DateTime.Now.Date); 

必须以这种方式

db.SomeTable.Where(x => EntityFunctions.TruncateTime(x) > EntityFunctions.TruncateTime(DateTime.Now.Date)); 

编写有什么办法,我可以向 EF 添加功能,或更改此行为,因为 LinqToSql 没有这些奇怪的语法

i'm intend to use both Linq to sql and EF 4.x, in same project (for some reason),

but there are some stuff in EF, that IMO is "Weird" like this:

db.SomeTable.Where(x => x.Date > DateTime.Now.Date); 

which must be written in this way

db.SomeTable.Where(x => EntityFunctions.TruncateTime(x) > EntityFunctions.TruncateTime(DateTime.Now.Date)); 

Is there any way, I can add functionalities to EF, or change this behavior, because LinqToSql don't have these weird syntax

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

路还长,别太狂 2024-12-25 12:56:20

实际上可以拦截查询并重写它。请参阅 IQueryable.ProviderIQueryable.Expression 属性。但这涉及编写自定义 ExpressionVisitor 来转换调用,并且很快就会变得复杂。

如果上面的代码是您遇到的 Linq-To-SQL 和 EF 之间唯一不匹配的地方,您可以像这样重写查询:

db.SomeTable.Where(x => x.Year == DateTime.Today.Year && x.Month == DateTime.Today.Month && x.Day == DateTime.Today.Day)

我很确定 EF 应该支持这种比较,Linq-To-Sql 也应该支持。

如果您想尝试第一种解决方案,我建议您为 EF 返回的 ObjectSet 创建一个 IQueryable 包装器,并在执行时设置断点简单的查询并查看表达式树实际上如何存储在查询中,这可能会给人一个要查找什么以及用什么替换它的印象。

Actually it is possible to intercept the query and rewrite it. See the IQueryable.Provider and IQueryable.Expression properties. But this involves writing a custom ExpressionVisitor to translate the call and gets complicated a very quickly.

If this code above is the only mismatch between Linq-To-SQL and EF you encountered, you could rewrite the query like this:

db.SomeTable.Where(x => x.Year == DateTime.Today.Year && x.Month == DateTime.Today.Month && x.Day == DateTime.Today.Day)

I'm pretty sure that EF should support this comparison and so should Linq-To-Sql.

If you want to try the first solution, I recommend you create a IQueryable<T>-wrapper for the ObjectSet<T> returned by the EF and set a breakpoint when performing simple queries and see how the expression tree is actually stored within the query, this might give an impression of what to look for and what to replace it with.

那片花海 2024-12-25 12:56:20

无法更改 EF 动态解析查询的方式。

您可以即时捕获查询并使用 http://metalinq.codeplex.com/ 编辑它们,但是可能是一项相当大的工作。

您可以重写您的查询,以便它适用于两者

There is no way to change the way that EF parses queries on the fly.

You can capture the queries on the fly and edit them using http://metalinq.codeplex.com/ however that might be a fair bit of work.

You can rewrite your query so it works on both though

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文