3

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
nacho10f
  • 5,816
  • 6
  • 42
  • 73

2 Answers2

2

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?

How to load Many to many LINQ query?

and tons more.

Community
  • 1
  • 1
Iain Galloway
  • 18,669
  • 6
  • 52
  • 73
0

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)

Dan McClain
  • 11,780
  • 9
  • 47
  • 67