在LINQ to Entities中将字符串转换为int?

kan*_*oid 5 linq-to-entities entity-framework

我必须将一个string值转换为int,但似乎 LINQ to Entities 不支持这一点。

对于以下代码,我收到错误消息。

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;
Run Code Online (Sandbox Code Playgroud)

LINQ to Entities 无法识别方法“ Int32 ToInt32 (System.String)”,并且此方法无法转换为存储表达式。

Ank*_*kur 4

在 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;
Run Code Online (Sandbox Code Playgroud)