tags:

views:

96

answers:

2
+2  Q: 

Linq many to many?

Say I have products and receipts in a many to many relation. Is there any way I can directly query product.receipts or receipt.products and get the Iqueryable without having to reference the join_table at all?

A: 

Linq to Entities and the Entity Framework supports many to many relations. I know Linq to Sql does not, and I think (not sure) Linq to NHibernate does support many to many. (I know NHibernate supports many-to-many)

phsr
+2  A: 

I assume you're using Linq-to-SQL.

The answer is "no, but..."

You can work with many-many relationships in Linq-to-SQL, but you do need to have a separate type representing the junction table.

If you just want to e.g. databind against a child property of a model object you can do something really simple like:-

public partial class Order
{
  public IEnumerable<Product> Products
  {
    get { return Order_Details.Select(x => x.Product); }
  }
}

Beware of the select-n-plus-one problem though if you then want to use that any time you're using a list of Orders.

More info: http://www.iaingalloway.com/many-to-many-relationships-in-linq-to-sql and here.

Also, there's a whole bunch of duplicate questions:-

http://stackoverflow.com/questions/1366686/linq-many-to-many-relationships-solution

http://stackoverflow.com/questions/79939/how-to-load-many-to-many-linq-query

and tons more.

Iain Galloway
This is the main reason why I moved from L2S to Entity Framework, and then hit a whole bunch of different issues ;)
Zhaph - Ben Duguid
Yup :) I generally say that if L2S "will do", go with it.
Iain Galloway