2009-11-16 63 views
4

當通過實體框架查詢數據庫時,是否有排除對象屬性值列表的方法?實體框架 - 排除值列表

我試圖滑頭拉這個數字:

List<String> StringList = new List<String>(); 
StringList.Add("ya_mama"); 
StringList.Add("has"); 
StringList.Add("fleas"); 

servicesEntities context = new servicesEntities(); 
var NoFleasQuery = (from x in context.person 
        where !StringList.Any(y => y.CompareTo(x.the_string_I_dont_want_it_to_be) == 0) // <--- the part where I thought I was slick 
        select x); 

它編譯,但之後,我跑了它,它給了我這個錯誤:

Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

「閉合型」?我的關閉如何!實體框架......你傷了我的心。

回答

3

什麼步驟呢?

var NoFleasQuery = (from x in context.person 
         where !StringList.Any(y => x.the_string_I_dont_want_it_to_be == y) 
         select x); 

它適用於我。但是生成的SQL相當糟糕:

SELECT 
1 AS [C1], 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
[Extent1].[Address_Id] AS [Address_Id] 
FROM [dbo].[Person] AS [Extent1] 
WHERE NOT EXISTS (SELECT 
    1 AS [C1] 
    FROM (SELECT 
     N'John Doe' AS [C1] 
     FROM (SELECT 1 AS X) AS [SingleRowTable1] 
    UNION ALL 
     SELECT 
     N'Jack Black' AS [C1] 
     FROM (SELECT 1 AS X) AS [SingleRowTable2]) AS [UnionAll1] 
    WHERE [Extent1].[Name] = [UnionAll1].[C1] 
) 

它建立一個子查詢這是其他子查詢的聯合,而不是使用「NOT IN」 ......也許不是很有效!

0

試試這個:

where !StringList.Contains(x.the_string_I_dont_want_it_to_be) 
+0

它給了我這個數字: LINQ to Entities不識別方法'Boolean Contains(System.String)'方法,並且這個方法不能被轉換成存儲表達式。 – 2009-11-16 09:27:52