Linq关联不同数据类型字段报错,求不修改数据库的解决方案
解决Linq关联查询中字段类型不匹配的问题
嗨,这个问题我之前也碰到过好几次,类型不匹配确实是Linq Join里的常见坑!你已经精准定位到了问题根源——Customer.CustomerId是对应数据库bigint的long类型,而CustomerGroupXref.CustomerId是对应数据库int的int类型,Linq要求Join的两端必须是完全匹配的类型,所以才会抛出那个错误。
在不修改数据库字段的前提下,只需要在Join的时候给其中一方做显式类型转换就行,这里有两个靠谱的方案:
方案1:将int类型字段转为long(更安全)
因为bigint的取值范围远大于int,把int转成long不会有数据溢出的风险,是最稳妥的选择:
var query1 = from c in db.Customers join cgx in db.CustomerGroupXrefs on c.CustomerId equals (long)cgx.CustomerId select new { Customer = c, CustomerGroupRef = cgx };
Linq to Entities会自动把这个转换翻译成SQL里的CAST(cgx.CustomerId AS BIGINT),数据库能完美执行这个转换并完成关联。顺带提一句,你的原代码里漏掉了select部分,Linq查询必须要有select(或group by这类终结操作)来生成结果集,记得补上哦。
方案2:将long类型字段转为int(需谨慎使用)
如果你能100%确定所有Customer.CustomerId的取值都在int的范围内(也就是不超过2^31-1),也可以反过来转换:
var query1 = from c in db.Customers join cgx in db.CustomerGroupXrefs on (int)c.CustomerId equals cgx.CustomerId select new { Customer = c, CustomerGroupRef = cgx };
但一定要注意,如果有CustomerId的值超过了int的最大值,这种转换会直接抛出溢出异常,所以只有在数据范围完全可控的情况下才推荐用这个方案。
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

