比较实体框架内的2个列表

时间:2014-03-04 14:34:11

标签: c# entity-framework

我有3个实体框架实体:

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.

知道如何解决此查询吗?

谢谢你, 米格尔

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

我不知道 SequenceEqual 是否与linq一起使用,但你可以查找。

http://msdn.microsoft.com/en-us/library/bb348567%28v=vs.110%29.aspx