当前位置: 首页 > 编程语言 > C#

运算符’==’不能应用于linq到实体的’System.Guid’和’string’类型的操作数分享

时间:2023-04-11 00:27:08 C#

C#学习教程:运算符'=='不能应用于linqtoentities中类型为'System.Guid'和'string'的操作数。'Guid'和'string'类型的操作数我收到此错误'operator'=='cannotbeappliedtotheoperandsoftype'System.Guid'and'string'inlinqtoentityframeworkbelowcode。在下面的代码中,CustomerId是Guid,customerProfileId是String。varaccountQuery=fromCinCustomerModel.CustomerProfilewhereC.CustomerId==customerProfileId//ErrorhereselectC;您不能直接将Guid与String进行比较。将字符串转换为Guid或将Guid转换为字符串。将Guid转换为字符串就像在变量上调用.ToString()一样简单,但重要的是要知道格式化Guid的方法不止一种。带或不带破折号:someguid。ToString()会给你类似B06A6881-003B-4183-A8AB-39B51809F196someGuid.ToString("N")会返回类似B06A6881003B4183A8AB39B51809F196如果你决定将C.CustomerId转换为字符串,请确保你知道customerProfileId格式。它可以是任何格式,因此最好将customerProfileId转换为guid:newGuid(customerProfileId)。这样做的缺点是,如果格式不正确,从字符串到Guid的转换会抛出异常。因此,如果您从表单字段或URL等用户输入中获取customerProfileId,则应首先对其进行验证。但是,如果您在查询之外提取到Guid的转换,您最终可能会获得更好的性能,因为比较Guid可能比比较String更快。varcustomerProfileGuid=newGuid(customerProfileId);//如果需要,包装在trycatch中varaccountQuery=fromCinCustomerModel.CustomerProfilewhereC.CustomerId==customerProfileGuidselectC;那是因为您不能将Guid等同于字符串。所以你需要先将Guid转换为字符串。通常我会建议:C.CustomerId.ToString().Equals(customerProfileId)但ToString()在LinqtoEntities中不存在。这个问题的答案-ProblemwithgettingGUIDstringvalueinLinq-To-Entityquery-可能有帮助。您必须将CustomerId转换为String(调用.ToString())或将customerProfileId转换为Guid(调用Guid.Parse()),然后比较它们。将其更改为:varaccountQuery=fromCinCustomerModel.CustomerProfilewhereC.CustomerId.ToString()==customerProfileIdselectC;或者将您的customerProfileId解析为Guid并在查询中使用它。问题是什么?显然其中一个值是Guid,另一个是String。您可以尝试以某种方式进行比较:C.CustomerId==newGuid(customerProfileId)takeC.CustomerIdisGuid。您可以执行C.CustomerId.toString()==customerProfileId或用新的Guid替换customerProfileId(customerProfileId)第二个应该更快,因为它只有一个转换,并且guid比较比字符串比较快。varaccountQuery=fromCinCustomerModel.CustomerProfilewhereC.CustomerId==newGuid(customerProfileId)//ErrorhereselectC;你需要从字符串生成新的guid,它应该工作上面是C#学习教程:operator'=='Cannotbeappliedtoallcontentsharedbylinqtoentity's'System.Guid'and'string'typeoperands,ifitisuseful给大家,需要了解更多C#学习教程,希望大家多多关注——本文来自网络合集,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢