Can't use ToString() in LINQ to Entities query

梦想与她 提交于 2019-12-08 09:23:54

问题


So I have the following code:

string searchQuery = collection["query"];    
var srmas = (
    from SRMAs in db.SRMAs
    join SRMAStatus in db.SRMAStatus on SRMAs.Id equals SRMAStatus.Id
    join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
    join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
    join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
    where ids.Contains(SRMAs.Status) 
    && 
    (
        searchQuery.Contains(PurchaseOrders.suppliersOrderNumber)
        ||
        searchQuery.Contains(SRMAs.PONumber.ToString())
    )
    select new
    {
        SRMAs.Id,
        SRMAs.PONumber,
        SRMAs.CreatedOn,
        Suppliers.SupplierName,
        SRMAStatus.StatusName,
        PurchaseOrders.PODate, PurchaseOrders.suppliersOrderNumber
    }
).ToList();

Where searchQuery is a string variable.

I have to actually use IN clause ofr PONumber and for that purpose I am using Contains which gives error mentioned in title. How do I check non String values?


回答1:


you could give SqlFunctions.StringConvert a shot, it'll marry you to sql server and requires .Net 4+

searchQuery.Contains(SqlFunctions.StringConvert((decimal)SRMAs.PONumber))

the function seems a little twitchy, when I was spinning up a sample I had to convert my int to a decimal to avoid a Ambigious Invoication build error.




回答2:


One apporach would be to convert searchQuery to the numeric datatype that the PONumber is, and you are all set.




回答3:


EF 4 does not support ToString() Method on queries. Either you need to update it to EF6 or you can use SqlFunctions.StringConvert function as follows.

string searchQuery = collection["query"];    
var srmas = (
    from SRMAs in db.SRMAs
    join SRMAStatus in db.SRMAStatus on SRMAs.Id equals SRMAStatus.Id
    join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
    join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
    join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
    where ids.Contains(SRMAs.Status) 
    && 
    (
        searchQuery.Contains(PurchaseOrders.suppliersOrderNumber)
        ||
        searchQuery.Contains(SqlFunctions.StringConvert((double)SRMAs.PONumber))
    )
    select new
    {
        SRMAs.Id,
        SRMAs.PONumber,
        SRMAs.CreatedOn,
        Suppliers.SupplierName,
        SRMAStatus.StatusName,
        PurchaseOrders.PODate, PurchaseOrders.suppliersOrderNumber
    }
).ToList();


来源:https://stackoverflow.com/questions/26146272/cant-use-tostring-in-linq-to-entities-query

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