How to access many-to-many table via Entity Framework? asp.net

断了今生、忘了曾经 提交于 2020-01-22 16:49:52

问题


How do I read a many-to-many table via EF? I have no idea how to use the many-to-many table. Let's say Product_Category where it got ProductID and CategoryID.

How can I access it trough e.g.

using(Entities db = new Entities)
{
    /* cant access these here.. */}

method?? I can however reach Product_Category, but cant access its ProductID or CategoryID.

I want to list every product e.g. where Product_Category.CategoryID == Category.ID.

I have never used many-to-many tables before, so I appreciate some simple examples how to access them trough EF in asp.net.

Thanks


回答1:


Navigation properties are your friend here. Unless you have other properties in the junction table, you don't need it. This is why there is no Product_Category in your models. So say your models are:

public class Product
{
    public Product()
    {
        this.Categories = new HashSet<Category>();
    }
    public int ProductId { get; set; }
    public string ProductName { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public Category()
    {
        this.Products = new HashSet<Product>();
    }

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

So now if you want all products in a category you can do something like:

var productsInCategory = db.Categorys
                      .Where(c => c.CategoryId == categoryId)
                      .SelectMany(c => c.Products);

If you do want an explicit junction tables see this: https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/




回答2:


You have to join the product and category tables with the bridge table Product_Category to retrieve the required product info.

using(eShopEntities db = new eShopEntities)
{
    var products = (from p in db.Product_Category 
                    join ProductTable pt on p.ID = pt.ProductID
                    join Category c on c.ID = P.CategoryID 
                    select new 
                           {
                                p.ID,
                                p.Name,
                                p.Description,
                                p.Price
                           }).ToList();
}


来源:https://stackoverflow.com/questions/35858672/how-to-access-many-to-many-table-via-entity-framework-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!