Judo
Judo

Reputation: 5247

Linq to Entities Querying a Many-to-Many Relationship

I have a Tag and an Article object with a many-to-many relationship using Entity Framework 4.1. I just want to retrieve a list of Articles which have a Tag. However the below code fails:

var db = new ArticleContext();
        var tag = db.Tags.Find(tagId);
        var articles= from article in db.Articles
                       where article.Tags.Contains(tag)
                       select article; 

The error is "Only primitive types ('such as Int32, String, and Guid') are supported in this context." I understand that this is a known issue with EF ( http://msdn.microsoft.com/en-us/library/bb896317.aspx#RefNonScalarClosures ) but what is the best workaround?

Upvotes: 1

Views: 550

Answers (1)

Eranga
Eranga

Reputation: 32447

Try this

var articles= from article in db.Articles
               where article.Tags.Any(tag => tag.Id == tagId)
               select article; 

Upvotes: 2

Related Questions