Search code examples
c#sqlasp.netentity-frameworkmany-to-many

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


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


Solution

  • 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/