2016-02-05 60 views
0

我在LINQPad中測試了以下LINQ查詢。但它給了我這個錯誤:在LINQ查詢中使用'NOT IN'子句

Error Compiling Expression: Error Compiling Expression: The best overloaded method match for 'string.Contains(string)' has some invalid arguments Argument '1': cannot convert from 'System.Linq.IQueryable' to 'string'

(from t in db.ASN_ITEM 
join t0 in db.ASN_MASTER on t.AWB_NO equals t0.AWB_NO 
join t1 in db.ITEM_MASTER on t.ITEM_MASTER.ITEM_CODE equals t1.ITEM_CODE 
where 
    (t.TOT_QTY - t.SCND_QTY) != 0 && 
    !t.AWB_NO.Contains((from t2 in db.ASN_ITEM 
        where 
        t2.SCAN_STAT != 2 
         select new { 
         t2.AWB_NO 
         }).Distinct()) && 
    t.AWB_NO == "E1000001" 
select new { 
    t.AWB_NO, 
    ASN_DATE = t.REC_DATE, 
    t.PALLET, 
    t.CARTON, 
    t.TOT_QTY, 
    t.SCND_QTY, 
    VAR_QTY = (System.Int32?)(t.SCND_QTY - t.TOT_QTY), 
    REMARKS = 
    (t.TOT_QTY - t.SCND_QTY) == 0 ? "No Variance" : 
    (t.TOT_QTY - t.SCND_QTY) > 0 ? "Less Qty" : 
    (t.TOT_QTY - t.SCND_QTY) < 0 && 
    t.TOT_QTY != 0 ? "Excess Qty" : 
    t.TOT_QTY == 0 && 
    t.SCND_QTY != 0 ? "Excess Item" : null, 
    t1.PART_NO 
}).Distinct() 

我得到這個錯誤,當我在下面給出的條件在where子句:

!t.AWB_NO.Contains((from t2 in db.ASN_ITEM 
       where 
       t2.SCAN_STAT != 2 
        select new { 
        t2.AWB_NO 
        }).Distinct()) 
在SQL查詢

其實,這正是我需要的(如下):

WHERE ASN_ITEM.AWB_NO NOT IN (SELECT DISTINCT AWB_NO FROM ASN_ITEM WHERE SCAN_STAT !=2) 
+1

我想這是因爲你的'選擇新{...}''裏面包含(...)'創建是一種新的匿名類型。你必須將其解析爲字符串或創建'新字符串{...}'。 –

+0

假設't2.AWB_NO'是一個字符串,您可以使用'select t2.AWB_NO'而不是使用'new'關鍵字的投影 –

回答

2

你應該以相反的方式做到這一點。在子查詢呼叫Contains(),在有多個項目的一個:

!(from t2 in db.ASN_ITEM 
    where t2.SCAN_STAT != 2 
    select t2.AWB_NO 
).Distinct() 
.Contains(t.AWB_NO) 

此外,你必須直接選擇AWB_NO,如上圖所示,而不是投射到匿名類型。執行後者將阻止使用Contains(),因爲集合中的項目類型將與作爲參數Contains()傳遞的對象類型不同。

0

從您的代碼中,我收集到AWB_NO是一個字符串。如果是這樣,那麼你在這裏做什麼:

!t.AWB_NO.Contains((from t2 in db.ASN_ITEM 
       where 
       t2.SCAN_STAT != 2 
        select new { 
        t2.AWB_NO 
        }).Distinct()) 

轉換爲這樣的:「這不是真的,一個字符串ABW_NO包含(和它的thisContains,不this)的匿名一些不同元素的表鍵入一個字符串屬性「。這是沒有意義的。這不是「不在」查詢。您正在檢查單個String是否包含一組匿名類型對象。

,如果你想使用一個String.Contains,並檢查是否一個字符串包含另一個字符串,那麼這會更有意義(可能不是你想要的,雖然什麼):

!t.AWB_NO.Contains((from t2 in db.ASN_ITEM 
       where 
       t2.SCAN_STAT != 2 
        select t2.AWB_NO).FirstOrDefault()) 

您可能會有所幫助:

How would you do a "not in" query with LINQ?

"NOT IN" clause in LINQ to Entities