SqlFunctions.StringConvert,。。。。。
C#(50) 网络
版权声明:本文为博主原创文章,未经博主容许不得转载。框架
一、在工做中碰到这样一个问题:ide
使用linq时,须要查询两个表,在这两张表中关联字段分别是int,和varchar()也就是string,在linq中对这两个字段进行关联,post
若是强制类型转换两个不一样类型的字段,就会报响应的扩展方法没法自动推断参数类型的问题(好比:我用的是groupjoin扩展方法),this
若是进行了常规的类型转换,好比将int字段对应的转换为string(ToString方法),这时编译的时候不会有问题了。spa
可是在运行的时候会报以下错误:设计
LINQ to Entities 不识别方法"System.String ToString()",所以该方法没法转换为存储表达式.code
二、解决方法:orm
使用System.Data.Objects.SqlClient.SqlFunctions.StringConvert()对相应的字段进行转换,结果能够了。ci
好比:
我有问题的Linq是下面这个:
var borrowLeftOutJoinLog =
query.GroupJoin(
groupRtnToolByID,
c => c.ID.ToString(),
d => d.BizID, (g, f) => new { Item = g, Detail = f })
.SelectMany(detail => detail.Detail.DefaultIfEmpty(), (a, b) => new { a.Item, RtnSum = (decimal?)b.RtnSum })
.Where(a => (a.RtnSum ?? 0) < a.Item.TBor_Qty)
.Select(a => a.Item);
注意:上面的ID和BizID是有关联的,可是在两个表中分别被设计成了int,string,因此这里对ID进行了ToString的转换,结果出现了上面提示的错误。
运用解决方法后的语句以下:
var borrowLeftOutJoinLog =
query.GroupJoin(
groupRtnToolByID,
c => System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)c.ID),
d => d.BizID, (g, f) => new { Item = g, Detail = f })
.SelectMany(detail => detail.Detail.DefaultIfEmpty(), (a, b) => new { a.Item, RtnSum = (decimal?)b.RtnSum })
.Where(a => (a.RtnSum ?? 0) < a.Item.TBor_Qty)
.Select(a => a.Item);
三、后感:
遇到这个问题后,本身尝试了解决,但是都行不通,因而转而求助网络(感谢这个时代吧!!!),
也看到了几篇关于这个的解决方法,其中就包括ToString方法,并且还言之凿凿,再不就是说一些框架,底层问题,
难道我为了这个芝麻大点的事,也要去本身重写,去实现不少内容吗??
若是是,只能说我选错了技术,它还不成熟。
但是,结果不是这样的,Linq出来已经好久了,它包含的内容也是不少,不该该是这样的,因此我继续找
在这里我找到了:
http://stackoverflow.com/questions/1066760/problem-with-converting-int-to-string-in-linq-to-entities
这句介绍了问题的缘由:StingyJack, the problem is with the ELINQ (linq 2 entities), because it translates your code to SQL, and when it comes to an inner ToString request, it doesn't know how to translate 'ToString' to SQL. Unlike with linq 2 objects, when there is no translation, and everything is CLR lambdas, then it's performed directly on the requested objects;
下面这个给了具体的解决方法:
With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this: var items = from c in contacts select new ListItem { Value = SqlFunctions.StringConvert((double)c.ContactId), Text = c.Name };
|
|||||||||||||||||||||
|
因此,我以为回答别人问题时要慎重,要针对别人给出的条件本身去试验,不能简单凭经验,不能说空话,更不能想固然。
给出结果要直接(固然若是要是一语中的,切中要害,那固然不用直接给出,但是我没有这样的功力,起码在linq上没有)