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?
-
3Linq to SQL or Linq to Entities or Linq to NHibernate or ... ? – Rob Fonseca-Ensor Feb 01 '10 at 12:47
-
1@IainGalloway Just because your answer is C#, doesn't mean the question was C#. Was that really worth the edit? – Rawling May 06 '15 at 11:06
2 Answers
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/2015/06/many-to-many-relationships-in-linq-to-sql.html and here.
Also, there's a whole bunch of duplicate questions:-
LINQ many-to-many relationships: Solution?

- 1
- 1

- 18,669
- 6
- 52
- 73
-
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 Feb 01 '10 at 16:38
-
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)

- 11,780
- 9
- 47
- 67