use*_*184 13 .net c# linq linq-to-entities entity-framework
我收到此错误'运算符'=='无法应用于linq类型'System.Guid'和'string''的操作数到代码下面的entityframework.在下面的代码中,CustomerId是Guid,customerProfileId是字符串.
var accountQuery = from C in CustomerModel.CustomerProfile
where C.CustomerId == customerProfileId // Error here
select C;
Run Code Online (Sandbox Code Playgroud)
Mar*_*len 24
您无法直接将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的转换将抛出异常.因此,如果您customerProfileId从用户输入(如表单字段或URL)获得,则应首先验证它.
但是,如果您在查询之外将转换拉到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;
Run Code Online (Sandbox Code Playgroud)
那是因为你不能将 Guid 和字符串等同起来。
所以需要先将Guid转换为字符串。通常我会建议:
where C.CustomerId.ToString().Equals(customerProfileId)
Run Code Online (Sandbox Code Playgroud)
但ToString()在 Linq to Entities 中不存在。
这个问题的答案 - Problem getting GUID string value in Linq-To-Entity query - 可能会有所帮助。
| 归档时间: |
|
| 查看次数: |
22306 次 |
| 最近记录: |