运算符’==’不能应用于linq到实体的’System.Guid’和’string’类型的操作数
我收到此错误’运算符’==’不能应用于linq中类型’System.Guid’和’string”的操作数到代码下面的entityframework。 在下面的代码中,CustomerId是Guid,customerProfileId是字符串。
var accountQuery = from C in CustomerModel.CustomerProfile where C.CustomerId == customerProfileId // Error here select C;
您无法直接将Guid与字符串进行比较。 将字符串转换为Guid或将Guid转换为字符串。
将Guid转换为字符串就像在变量上调用.ToString()
一样简单,但重要的是要知道格式化Guid的方法不止一种。 有或没有破折号:
someguid.ToString()
会给你一些像B06A6881-003B-4183-A8AB-39B51809F196
someGuid.ToString("N")
将返回类似B06A6881003B4183A8AB39B51809F196
东西
如果您决定将C.CustomerId
转换为字符串,请确保您知道customerProfileId
格式。
如果它可以是任何一种格式,那么最好将customerProfileId
转换为guid: new Guid(customerProfileId)
。
这样做的缺点是,如果格式不正确,从字符串到Guid的转换将抛出exception。 因此,如果您从用户输入(如表单字段或URL)获得customerProfileId
,则应首先validation它。
但是,如果您在查询之外将转换提取到Guid,您可能最终会获得更好的性能,因为比较Guids可能比比较字符串更快。
var customerProfileGuid = new Guid(customerProfileId); // wrap in try catch if needed var accountQuery = from C in CustomerModel.CustomerProfile where C.CustomerId == customerProfileGuid select C;
那是因为你不能把Guid和一个字符串等同起来。
所以你需要先将Guid转换成字符串。 通常我会建议:
where C.CustomerId.ToString().Equals(customerProfileId)
但Linq to Entities中不存在ToString()
。
这个问题的答案 – 在Linq-To-Entity查询中获取GUID字符串值的问题 – 可能会有所帮助。
您必须将CustomerId
转换为字符串(调用.ToString()
)或customerProfileId
为Guid
(调用Guid.Parse()
)然后比较它们。
将其更改为:
var accountQuery = from C in CustomerModel.CustomerProfile where C.CustomerId.ToString() == customerProfileId select C;
或者将您的customerProfileId解析为Guid并在查询中使用它。
问题是什么?
显然,其中一个值是Guid,而另一个是字符串。 您可以尝试以某种方式进行比较:
C.CustomerId ==新的Guid(customerProfileId)取C.CustomerId是Guid。
你能做一个C.CustomerId.toString()== customerProfileId或用new Guid替换customerProfileId(customerProfileId)
第二个应该更快,因为它只有一个转换,guid比较比字符串比较快。
var accountQuery = from C in CustomerModel.CustomerProfile where C.CustomerId == new Guid(customerProfileId) // Error here select C;
你需要从字符串生成新的guid,它应该工作
上述就是C#学习教程:运算符’==’不能应用于linq到实体的’System.Guid’和’string’类型的操作数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1026678.html