How to configure many to many relationship using entity framework fluent API

后端 未结 4 2060
悲哀的现实
悲哀的现实 2020-11-27 20:41

I\'m trying to set up a many to many relationship in EF code first but the default conventions is getting it wrong. The following classes describes the relationship:

<
相关标签:
4条回答
  • 2020-11-27 21:17

    What EF has suggested is a one-to-many relationship.

    One Account can have many Products, i.e. each Product has an Account_Id

    If you want a many to many relationship (and create an intermediary table), the following should work

    class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Account> Accounts { get; set; }
    }
    
    class Account
    {        
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-27 21:24
            public AccountProductsMap()
        {
            this.ToTable("AccountProducts");
            this.HasKey(cr => cr.Id);
    
            this.HasMany(cr => cr.Account)
                .WithMany(c => c.Products)
                .Map(m => m.ToTable("AccountProducts_Mapping"));
        }
    
    0 讨论(0)
  • 2020-11-27 21:33

    Code first is creating tables in right relational way. When

    One Account can have many Products.

    Products table should store key for its Account, as it actually does now.

    What you are trying to see in db, is many-to-many relationship, not one to many. If you want to achieve that with code first, you should redesign your entities

    class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Account> Accounts { get; set; }
    }
    
    class Account
    {        
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
    

    In this case, one product can have many accounts, and one account can have many products.

    0 讨论(0)
  • 2020-11-27 21:36
    modelBuilder.Entity<Account>()
                .HasMany(a => a.Products)
                .WithMany()
                .Map(x =>
                {
                    x.MapLeftKey("Account_Id");
                    x.MapRightKey("Product_Id");
                    x.ToTable("AccountProducts");
                });
    
    0 讨论(0)
提交回复
热议问题