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:
<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; }
}
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"));
}
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.
modelBuilder.Entity<Account>()
.HasMany(a => a.Products)
.WithMany()
.Map(x =>
{
x.MapLeftKey("Account_Id");
x.MapRightKey("Product_Id");
x.ToTable("AccountProducts");
});