Entity Framework many-to-many question

后端 未结 2 1022
误落风尘
误落风尘 2020-12-31 18:56

Please help an EF n00b design his database. I have several companies that produce several products, so there\'s a many-to-many relationship between companies and products. I

2条回答
  •  醉梦人生
    2020-12-31 19:31

    I would just like to add the following to Samuel's answer:

    If you want to directly query from one side of a many-to-many relationship (with payload) to the other, you can use the following code (using the same example):

    Company c = context.Companies.First();
    IQueryable products = c.Company_Products.Select(cp => cp.Product);
    

    The products variable would then be all Product records associated with the Company c record. If you would like to include the SKU for each of the products, you could use an anonymous class like so:

    var productsWithSKU = c.Company_Products.Select(cp => new {
      ProductID = cp.Product.ID,
      Name = cp.Product.Name,
      Price = cp.Product.Price,
      SKU = cp.SKU
    });
    foreach (var 
    

    You can encapsulate the first query in a read-only property for simplicity like so:

    public partial class Company
    {
      public property IQueryable Products
      {
        get { return Company_Products.Select(cp => cp.Product); }
      }
    }
    

    You can't do that with the query that includes the SKU because you can't return anonymous types. You would have to have a definite class, which would typically be done by either adding a non-mapped property to the Product class or creating another class that inherits from Product that would add an SKU property. If you use an inherited class though, you will not be able to make changes to it and have it managed by EF - it would only be useful for display purposes.

    Cheers. :)

提交回复
热议问题