Convert string to int in LINQ to Entities?

你说的曾经没有我的故事 提交于 2019-12-20 01:33:46

问题


I have to convert a string value to int, but it seems LINQ to Entities does not support this.

For the following code, I am getting an error.

var query = (from p in dc.CustomerBranch
             where p.ID == Convert.ToInt32(id) // here is the error.
             select new Location()
             {
                 Name      = p.BranchName,
                 Address   = p.Address,
                 Postcode  = p.Postcode,
                 City      = p.City,
                 Telephone = p.Telephone
             }).First();
return query;

LINQ to Entities does not recognize the method 'Int32 ToInt32 (System.String)', and this method can not be translated into a store expression.


回答1:


Do the conversion outside LINQ:

var idInt = Convert.ToInt32(id);
var query = (from p in dc.CustomerBranch
             where p.ID == idInt 
             select new Location()
             {
                 Name      = p.BranchName,
                 Address   = p.Address,
                 Postcode  = p.Postcode,
                 City      = p.City,
                 Telephone = p.Telephone
             }).First();
return query;



回答2:


No they wouldn't. Think of it this way: both ToString() and Parse() are methods on the objects. Since LINQ to Entities tries to convert your LINQ expression to SQL, those are not available.

If one needs to do this in the query, it might be possible with Cast, which should be available in LINQ to Entities. In the case of ToString, you could use SqlFunctions.StringConvert().



来源:https://stackoverflow.com/questions/7399602/convert-string-to-int-in-linq-to-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!