I’m trying to query Posts based on a list of 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;}
}
Now I want to return posts based a list of tags:
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
When a post contains one or more tags that also exists in searchTags it should be included in the result. I have tried the following:
var q = from s in Context.Registrations
where s.Tags.Intersect(tagList)
select s;
Error: 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;
Runtime error: 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.
Any ideas?
— update Jan. 4:
The answers point to the right solution, but in my code I still have the NotSupportedException. Is it possible the nullable integer causes this since it is not a primitive type?
Today I encountered this problem again, and decided to solve it. The problem of my question is that the
IList<Tag> searchTags = ParseTagsFromSearchString("tag1,tag2,tag3");produces a list, which will cause an exception when used in an intersect expression of another query in entity framework. The right thing to do is this: