2014-03-04 56 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”的常量值。只有原始类型或枚举类型在此上下文中受支持。任何想法为什么? –