在LINQ中将字符串转换为int到实体?

在LINQ中将字符串转换为int到实体?

问题描述:

我必须将string值转换为int,但似乎LINQ to Entities不支持此功能.

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无法识别方法'Int32 ToInt32 (System.String)',并且该方法不能转换为商店表达式.

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

在LINQ之外进行转换:

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;