使用 Linq 2 EF,如何找到以“x”开头的 guid?
使用 Linq2Entities (EF4),我需要查询具有 Guid
属性(称为 id
)的实体。我需要查询我的实体是否有任何 id
以给定前缀开头的记录。
本质上,我需要类似
from items in myEntity
where items.id.ToString().StartsWith(prefix)
// rest of the query
现在,我知道 L2EF 不支持使用 ToString()
转换 Guid
成员。
SqlFunctions.StringConvert()
帮助器也不支持它,因为它不接受 Guid
参数。
而且我无法使用 SQL 的 LIKE
,因为
from items in myEntity
where items.id like 'prefix%'
L2EF 也不支持它。
到目前为止,我发现的所有建议都建议使用 Contains()
,但这与 starts with
根本不一样......在 的情况下例如,Guid 可能会在最后 13 个字符中找到前 8 个字符。
那么,您将如何使用 L2EF 查询具有以“prefix”开头的 Guid 的记录?
我可以想到一些技巧,例如将后端 SQL 数据库上的 uniqueidentifier
字段转换为 varchar()
,但我真的很想了解我是否只是在采取类似的做法之前就已经做错了。
Using Linq2Entities (EF4), I need to query an entity that has a Guid
property (call it id
). I need to query whether or not my entity has any records that have id
s starting with a given prefix.
In essence, I need something like
from items in myEntity
where items.id.ToString().StartsWith(prefix)
// rest of the query
Now, I know that L2EF doesn't support conversions of Guid
members using ToString()
.
The SqlFunctions.StringConvert()
helper doesn't support it either as it doesn't accept a Guid
argument.
And I can't use SQL's LIKE
, as in
from items in myEntity
where items.id like 'prefix%'
because it's also not supported by L2EF.
All of the recommendations I've found so far suggest using Contains()
, but that's simply not the same as starts with
.... In the case of Guid
s, for example, the first 8 chars might be found in the last 13 characters.
So, how would YOU use L2EF to query records that have a Guid starting with "prefix" ?
I can think of some hacks like converting the uniqueidentifier
field on the back end SQL database to a varchar()
, but I'd really like to understand if I'm just doing it wrong before resorting to something like that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两种选择:
1)更改实体数据模型,以便无论“x”表示什么,它都会被移动到该实体上的属性,而不是紧密耦合到唯一的ID
2)将整个实体列表放入集合中,然后将它们加载到集合中内存,遍历并对集合执行 id.ToString().Contains() 查询。一旦它被加载到内存中,CLR 将允许这样做。不过,开销太可怕了。
如果可能的话我会选择#1。
Two options:
1) change your entity data model so that whatever "x" signifies, it is moved to a property on that entity instead of tightly coupled to the unique id
2) get the whole list of entities into a collection, then after they are loaded into memory, go through and do a id.ToString().Contains() query on the collection. Once it has been loaded into memory the CLR will allow this. Though, horrible overhead.
I'd go with #1 if possible.
在您的上下文中使用 ExecuteStoreQuery 并直接针对您的上下文执行自定义 SQL 语句。例如:
另外,请查看此 MSDN 示例。
Use
ExecuteStoreQuery
on your context and execute a custom SQL statement directly against your context. Something like:Also, check out this MSDN example.