2014-03-04 54 views
2

我有3個實體框架的實體:比較2名列表內部實體框架Where子句

public class Tag { 
    public Int32 Id { get; set; } 
    public String Name { get; set; } 
} 

public class Book { 
    public Int32 Id { get; set; } 
    public String Name { get; set; } 
    public IList<Tag> Tags { get; set; } 
} 

public class Post { 
    public Int32 Id { get; set; } 
    public String Name { get; set; } 
    public IList<Tag> Tags { get; set; } 
} 

鑑於一本書,我需要得到所有具有完全相同的標籤作爲書的帖子。

IList<Tags> tags = new List<Tag> { new Tag { Id = 1 }, new Tag { Id = 2 } }; 

Book book = new Book { Tags = tags }; 

context.Posts.Where(x => 
    new HashSet<Int32>(x.Tags.Select(y => y.Id)).SetEquals(book.Tags.Select(y => y.Id))) 
.ToList(); 

我得到以下錯誤:

An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code 

Additional information: LINQ to Entities does not recognize the method 'Boolean SetEquals(System.Collections.Generic.IEnumerable`1[System.Int32])' method, and this method cannot be translated into a store expression. 

任何想法如何解決這個查詢?

謝謝你, 米格爾

回答

0
from p in context.Posts 
let tags = context.Books(b=>b.ID == bookId).Select(b=>b.Tags)//you might need .SelectMany 
where p.Tags.All(t=>tags.Any(bt=>bt.Id == t.Id)) 
select p 

只做lambda表達,它可能會更好,在率先拿到標籤,它可能會更好,即使在第一個選項。

var tags = context.Books(b=>b.ID == bookId).Select(b=>b.Tags)//you might need .SelectMany 

var result = context.Posts.Where(p=>p.Tags.All(t=>tags.Any(bt=>bt.Id == t.Id)).ToList(); 
+0

我使用lambda表達式,因爲我使用的是庫...您的代碼可以被轉換爲Lambda表達式? –

+0

不知道爲什麼它必須是存儲庫的lambda,但是可以完成。 –

+0

我試過你的解決方案,但是我得到的錯誤與我以前的gad相似:在mscorlib.dll中發生類型'System.NotSupportedException'的異常,但未在用戶代碼中處理。其他信息:無法創建類型爲「Proj.Data.Entities.Tag」的常量值。只有原始類型或枚舉類型在此上下文中受支持。任何想法爲什麼? –