Search code examples
c#-4.0entity-framework-4linq-to-entities

LINQ to Entities does not recognize the method 'System.String ToString()'


I am trying to build a Linq to Entities query that joins a table with a foreign key column of string and the related table ID has an integer ID. I know whoever designed the database schema screwed up, but unfortunately for whatever reasons, I can't change the database schema in this case.

Here is the error I get:

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

Here is the linq (to Entities) statement that causes it:

var query = from p in db.QBPOes
            join j in db.tblJobManagements on p.CustJob equals j.JobID
            join s in db.tblSuppliers on p.VendorID equals s.SupplierID.ToString()
            where p.ID == poID
            select new 
            {
                p.ID,
                p.Date,
                p.VendorID,
                p.FirstName,
                p.LastName,
                s.SupplierWorkPhone,
                s.SupplierFaxNumber,
                p.CompanyName,
            };

I am joining these tables because I want to get the supplier phone and fax number.


Solution

  • In order to cast p.VendorID into an integer you can use this workaround. The generated SQL might not be pretty, but it should work, unless p.VendorID can not be cast into an integer

    var query = from p in db.QBPOes
                let vendorId = db.QBPOes.Select(x => p.VendorID).Cast<int>().FirstOrDefault()
                join j in db.tblJobManagements on p.CustJob equals j.JobID
                join s in db.tblSuppliers on vendorId equals s.SupplierID
                where p.ID == poID
                select new 
                {
                    p.ID,
                    p.Date,
                    p.VendorID,
                    p.FirstName,
                    p.LastName,
                    s.SupplierWorkPhone,
                    s.SupplierFaxNumber,
                    p.CompanyName,
                };
    

    It might be better to cast s.SupplierID to string, so you would rearrange your query like so

    var query = from s in db.tblSuppliers
                let supplierID = db.tblSuppliers.Select(x => s.SupplierID).Cast<string>().FirstOrDefault()
                join p in db.QBPOes on supplierID equals p.VendorID
                join j in db.tblJobManagements on p.CustJob equals j.JobID
                where p.ID == poID
                select new 
                {
                  p.ID,
                  p.Date,
                  p.VendorID,
                  p.FirstName,
                  p.LastName,
                  s.SupplierWorkPhone,
                  s.SupplierFaxNumber,
                  p.CompanyName,
                };