在LINQ to Entities查询中不能使用ToString()

时间:2014-10-01 16:39:56

标签: c# linq entity-framework entity-framework-4 linq-to-entities

所以我有以下代码:

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();

searchQuery是字符串变量。

我必须实际使用IN PONumber的{​​{1}}子句,为此我使用Contains,它会在标题中提到错误。如何检查非String值?

3 个答案:

答案 0 :(得分:2)

你可以给SqlFunctions.StringConvert一个镜头,它会嫁给你的sql server并需要.Net 4 +

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

这个函数看起来有点抽搐,当我旋转一个样本时,我必须将我的int转换为十进制,以避免Ambigious Invoication构建错误。

答案 1 :(得分:0)

一种方法是将searchQuery转换为PONumber所属的数字数据类型,并且您已全部设置。

答案 2 :(得分:0)

EF 4不支持查询的ToString()方法。您需要将其更新为EF6,或者您可以使用SqlFunctions.StringConvert函数,如下所示。

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();