“无法在DateTime上调用方法"和其他限制 [英] "Cannot call methods on DateTime", and other limitations
问题描述
有人知道在编译时没有捕获到的LINQ to SQL查询限制的权威列表,以及(如果可能)该限制的解决方法吗?
Does anyone know of a definitive list of LINQ to SQL query limitations that are not trapped at compile time, along with (where possible) workarounds for the limitations?
到目前为止,我们的列表是:
The list we have so far is:
- 调用方法,例如
DateTime
上的.Date
- 未找到解决方法
- Calling methods such as
.Date
onDateTime
- no workaround found
- 简单,只需使用
== ""
代替
- 我们使用了
.OrderByDescending(x => x.WhateverProperty).First()
推荐答案
基本上,该列表很大……它是相对泄漏抽象法出现了,每个提供者都有不同的答案.
Basically, that list is huge... it is everything outside of the relatively small set of things that are handled. Unfortunately, the Law Of Leaky Abstractions kicks in, and each provider has different answers...
LINQ-to-Objects将做任何事情(相当多),因为它是委托. LINQ-to-SQL和Entity Framework具有不同的支持集.
LINQ-to-Objects will do anything (pretty much), since it is delegates; LINQ-to-SQL and Entity Framework have different sets of support.
通常,使用
DateTime
属性等取得了相当大的成功-但实际上,您将必须确保查询表达式包含在单元测试中,以便更改提供程序(或更新提供程序),您知道这一切仍然有效.In general, I've had a fair amount of success using the
DateTime
properties etc - but in reality, you're going to have to ensure that your query expressions are covered by unit tests, so that if you ever change providers (or the provider gets updated) you know it all still works.我猜想一种观点是根据TSQL来思考的.没有
BOTTOM n
,但是有一个TOP 1
(是OrderByDescending
);就string.IsNullOrEmpty
而言,您可能是个字面意义:foo.Bar == null || foo.Bar == ""
;并且使用DateTime.Date
您可能可以对DATEPART
/各种组件进行很多操作.I guess one view is to think in terms of TSQL; there is no
BOTTOM n
, but there is aTOP 1
(re theOrderByDescending
); In terms ofstring.IsNullOrEmpty
, you could be quite literal:foo.Bar == null || foo.Bar == ""
; and withDateTime.Date
you can probably do quite a bit withDATEPART
/ the various components.LINQ-to-SQL的另一个选择是将逻辑封装在UDF中-因此您可以编写一个使用
datetime
并返回datetime
的UDF,然后通过dbml将其公开到数据上下文中.然后,您可以在查询中使用它:Another option with LINQ-to-SQL is to encapsulate the logic in a UDF - so you could write a UDF that takes a
datetime
and returns adatetime
, and expose that via the dbml onto the data-context. You can then use that in your queries:where ctx.Date(foo.SomeDate) == DateTime.Today
但是,这种方法不一定能很好地利用索引.
This approach, however, doesn't necessarily make good use of indexes.
更新:
- The supported method translations etc are here.
- The supported query operations etc are here.
有关gory的全部详细信息,可以查看反射器中的
System.Data.Linq.SqlClient.PostBindDotNetConverter+Visitor
-特别是Translate...
方法;某些string
函数是单独处理的.因此,不是巨大选择-但这是实现细节.For the full gory details, you can look at
System.Data.Linq.SqlClient.PostBindDotNetConverter+Visitor
in reflector - in particular theTranslate...
methods; somestring
functions are handled separately. So not a huge selection - but this is an implementation detail.这篇关于“无法在DateTime上调用方法"和其他限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!