Reputation: 2750
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.
Upvotes: 5
Views: 19457
Reputation: 13
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()
.
Upvotes: -2
Reputation: 33657
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;
Upvotes: 4