LINQ多对多交叉口

Mar*_*ijn 6 c# linq entity-framework linq-to-sql

我正在尝试Posts基于以下列表进行查询Tags:

public class Post
{
  public int? Id {get;set;}
  public string Name {get;set;}
  public virtual ICollection<Tag> Tags {get;set;}
}
public class Tag
{
  public int? Id {get;set;}
  public string Name {get;set;}
  public vritual ICollection<Post> Posts {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

现在我想根据标签列表返回帖子: IList<Tag> searchTags = ParseTagsFromSearchString("tag1,tag2,tag3"); // this function checks the tags in the database, so all the primary keys are available in the list

当帖子包含一个或多个也存在于searchTags其中的标签时,应包含在结果中.我尝试过以下方法:

var q = from s in Context.Registrations
                    where s.Tags.Intersect(tagList)
                    select s;
Run Code Online (Sandbox Code Playgroud)

错误: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Models.Tag>' to 'bool'

var q = from s in Context.Registrations
                    where s.Tags.Any(t => tagList.Any(t2 => t.Id.Value == t2.Id.Value))
                    select s;
Run Code Online (Sandbox Code Playgroud)

运行时错误:有NotSupportedException: Unable to create a constant value of type 'Models.Tag'. Only primitive types ('such as Int32, String, and Guid') are supported in this context. 什么想法吗?

- 1月4日更新:答案指向正确的解决方案,但在我的代码中我仍然有NotSupportedException.可以为空的整数是否可能导致这种情况,因为它不是原始类型?

Mar*_*ijn 1

今天又遇到这个问题,决定解决一下。我的问题是生成IList<Tag> searchTags = ParseTagsFromSearchString("tag1,tag2,tag3");一个列表,当在实体框架中另一个查询的相交表达式中使用时会导致异常。正确的做法是:

var q = ParseTagsFromSearchString("tag1,tag2,tag3"); // this function will now build a query instead of a list
IList<Post> posts = (from s in Context.Posts where s.Tags.Intersect(q.AsEnumerable()).Any() select s).ToList();
Run Code Online (Sandbox Code Playgroud)