LINQ so far has been remarkably elegant, but to perform basic m2m queries it offers no solution I can imediately see.
What's worse is that while it works for any other table relationship, LINQ is not giving me an association in the class structure for my m2m table.
So I can do things like
artwork.artists.where(...)
//or
artist.Artworks.add(artwork)
but I can't do
artwork.artowrks_subjects.tagSubjects.where(...)
//or
tagSubject.artworks_subjects.add(artwork)
alt text http://img299.imageshack.us/img299/257/20090902122107.png
Is there a common pattern for solving this limitation?
Yes. Instead of many-to-many use two many-to-one relationships:
the way I have gotten M2M working in LINQ2SQL:
now the tagSubject entity will have a collection of artwork_subjects, and the artwork_subject will have a property of type artwork called Artwork. so you can now make a LINQ expression like
This largely depends on what framework you are using. It sounds like you are using LINQ-to-SQL, which is very literal about tables to objects. With Entity Framework, there is inbuilt support for many-to-many, in particular for the trivial case you've listed (a linking table with no additional properties). EF will generally spot this pattern, and hide the link table from the conceptual model (I can't remember, but it might need a spanning PK over the two FK columns).
Of course, this then goes sour if you want to add columns to the link-table; so in some ways I'd be tempted to leave it "as is".
With regards the
where
etc - how do you mean? You can do joins over the association, and you should be able to useAny
etc; do you have a concrete example of what you want to do?Found the solution myself. For automated relationships to work, both tables need primary keys (oops). Notice artworks_subjects is missing the PK symbol.