问题描述
我正在编写一个Entity Framework LINQ查询,其中我想将字符串解析为UNIQUEIDENTIFIER(aka GUID)作为 WHERE
子句的一部分:
I'm writing an Entity Framework LINQ query in which I want to parse a string into a UNIQUEIDENTIFIER (aka GUID) as part of the WHERE
clause:
public IEnumerable<User> Find(Guid guid)
{
return dbContext
.Users
.Where(user => Guid.Parse(user.GuidText) == guid);
}
我知道这在SQL中是可能的,因为我已经对其进行了测试:
I know this is possible in SQL because I've tested it:
SELECT *
FROM Users
WHERE CAST(GuidText AS UNIQUEIDENTIFIER) = @guid;
但是,我还没有找到生成 CAST
部分的方法.我尝试过:
However, I haven't found a way to generate the CAST
part. I've tried:
-
(Guid)user.GuidText
,它会生成编译器错误. -
Convert.ToGuid(user.GuidText)
,但此方法不存在. -
Guid.Parse(user.GuidText)
,但这会导致Entity Framework在转换LINQ查询时生成错误. -
新Guid(user.GuidText)
,但这会导致Entity Framework在转换LINQ查询时生成错误. -
(Guid)Convert.ChangeType(user.GuidText,typeof(Guid))
,但这会导致Entity Framework在转换LINQ查询时生成错误. -
SqlGuid.Parse(user.GuidText)
,但这会导致Entity Framework在转换LINQ查询时生成错误.
(Guid)user.GuidText
, which generates a compiler error.Convert.ToGuid(user.GuidText)
, but this method doesn't exist.Guid.Parse(user.GuidText)
, but this causes Entity Framework to generate an error when it translates the LINQ query.new Guid(user.GuidText)
, but this causes Entity Framework to generate an error when it translates the LINQ query.(Guid)Convert.ChangeType(user.GuidText, typeof(Guid))
, but this causes Entity Framework to generate an error when it translates the LINQ query.SqlGuid.Parse(user.GuidText)
, but this causes Entity Framework to generate an error when it translates the LINQ query.
我该如何实现?我愿意在最后的方法中将SQL嵌入代码中.
How can I achieve this? I'm willing to embed SQL in the code as a last resort.
推荐答案
EF运行时实际上支持将字符串转换为GUID作为强制转换操作,但是正如您所发现的那样,目前我们无法在LINQ中表达这一点.支持.
EF runtime actually supports converting from a string to a GUID as a cast operation, but as you find out there is currently no way of expressing this in LINQ that we support.
我能想到的最好的解决方法是使用Entity SQL:
The best workaround that I can think of is to use Entity SQL:
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
var query = objectContext.CreateQuery<User>(
"SELECT VALUE u FROM Context.Users AS u WHERE CAST(u.GuidText AS System.Guid) = @guid",
new ObjectParameter("guid", guid));
这篇关于如何将字符串解析为UNIQUEIDENTIFIER?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!