2017-07-24 63 views
1

似乎在EF Core的查詢如myContext.Books.Where(b => new [] { "harry potter", "the lord of the rings" }.Contains(b.Title.ToLower()))中,過濾部分不在sql server上執行,沒有'where'關閉構建。我正在使用postgresql和npgsql驅動程序,但我已經檢查過相同的行爲是爲MS SQL服務器。 所以,你知道是否有可能建立查詢系統將生成SQL WHERE這樣的條款(PostgreSQL的): where lower(title) in ('harry potter', 'the lord of the rings')ToLower in Array.Contains in Entity Framework核心

回答

1

您正在限制EF Core SQL翻譯。 Upto版本1.1.2 EF核心假設在Array.Contains(item)中,item將是成員表達式或EF.Property方法調用,指示屬性訪問。但在你的情況下,你有一個不同的方法調用,因爲你打電話ToLower(),因此EF核心無法識別模式,並且不會將Contains翻譯到服務器。

同時在修復不同的issue時刪除了此限制。 如果可能,現在EF Core會翻譯item。由於ToLower()是可以被翻譯的,所以它可以正常工作並生成IN聲明。該問題已在2.0.0-preview1中解決。所以它應該可以在EF Core的2.0版本中使用。

我使用EF Core 2.0.0的每晚構建測試了查詢。以下是生成的SQL。

SELECT [x].[Id], [x].[Title] 
FROM [Blogs] AS [x] 
WHERE LOWER([x].[Title]) IN (N'harry potter', N'the lord of the rings') 
1

你的LINQ語句似乎有點偏離做一個鬆散匹配所有。

class Program 
    { 
    static void Main(string[] args) 
    { 
     var contextMock = new List<Book> 
     { 
     new Book(1, "Harry Potter and The Sorcerer's Stone", "Fiction"), 
     new Book(2, "Harry Potter and The Secret Chamber", "Fiction"), 
     new Book(3, "Dune", "Fiction"), 
     new Book(4, "The Lord of The Rings The Fellowship of the Ring", "Fiction"), 
     new Book(5, "The Lord of The Rings Return of the King", "Fiction"), 
     new Book(6, "A Brief History of Time", "NonFiction") 
     }; 


     var wrong = contextMock.Where(x => (new[]{ "harry potter", "the lord of the rings" }).Contains(x.Title.ToLower())).ToList(); 
     var right = contextMock.Where(x => (new List<string> { "harry potter", "the lord of the rings" }).Any(y => x.Title.ToLower().Contains(y.ToLower()))).ToList(); 

     Console.ReadLine(); 
    } 
    } 
+0

它沒有幫助。正如我寫的,我希望EF用'where'('harry potter','the rings of the Lord's')中的lower(title)'生成sql,但現在它只生成'select ... from ...'獲取整個表格,然後在內存中進行過濾。 – hmisko

+0

???除非您重寫T4模板,否則EF不會生成查詢。 Postgresql只是數據庫的一種風格。除非你有其他的npgsql只是一個驅動程序。因此,如果沒有更多的數據,你只是提出一個謂詞,在哪裏,你是否把你失去匹配的意圖是錯誤的。如果它生成的地方你沒有提供這個細節。我剛剛看到了linq',(b => ...)',並且看到它的意圖是錯誤的。 – djangojazz