Adam Asham
Adam Asham

Reputation: 1519

Query a many to many relationship with Entity Framework and .NET 3.5

My problem is actually two-fold. First, I'm pretty new to EF but I've used it with some success by taking shortcuts earlier. Though, for this particular project I plan to take the time to learn.

What I have at this point is a very simplistic database structure:

Post
===================
Id     Title
-------------------
 1     Hello world
 2     Foo bar baz

Tag
===================
Id     Title
-------------------
 6     test
 7     todo

PostTags
===================
PostId     TagId
-------------------
     1         6
     1         7
     2         7

Using EF, it generates a model with two entities: Post and Tag.

What I'm trying to accomplish:

I'm attempting to query the model for all posts given an array of tagIds (6 and 7 for instance). However I can't figure out what I need to do to make that work. Previously I've cheated in the way that I added an auto-incremental PK to the mapping table (BlogPosts) and added it into the EF-model but it was more of an ugly hack in order to move forward. I'd rather learn how to do it right this time.

Upvotes: 4

Views: 547

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

This will work in EFv4. Try it in EFv1:

var tagIds = new int[] { 6, 7 };
var query = context.Tags
                   .Where(t => tagIds.Contains(t.Id))
                   .SelectMany(t => t.Posts);

Edit:

I checked it and collection valued parameters + Contains were added in EFv4 so above example doesn't work in EFv1. This thread in MSDN forum provides workaround to allow IN operator in EFv1. Another recommended workaround is simply upgrade to EFv4 because there are many other improvements including significant improvement of performance.

Upvotes: 1

Related Questions