Fix*_*xer 25 c# associations ef-code-first entity-framework-4.1
我试图首先在EF代码中建立多对多关系,但默认约定是错误的.以下类描述了这种关系:
class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
class Account
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
一个帐户可以有许多产品.
但是,EF约定将创建DB表,如下所示:
Products Table
--------------
Id
Name
Account_Id <- What is this?
Accounts Table
--------------
Id
Name
Run Code Online (Sandbox Code Playgroud)
这看起来不像是一个多对多的表结构?如何配置流畅的API以反映关系并创建中间表:
AccountProducts Table
---------------------
Account_Id
Product_Id
Run Code Online (Sandbox Code Playgroud)
Sla*_*uma 59
modelBuilder.Entity<Account>()
.HasMany(a => a.Products)
.WithMany()
.Map(x =>
{
x.MapLeftKey("Account_Id");
x.MapRightKey("Product_Id");
x.ToTable("AccountProducts");
});
Run Code Online (Sandbox Code Playgroud)
EF所建议的是一对多的关系.
一个帐户可以有许多产品,即每个产品都有一个Account_Id
如果您想要多对多关系(并创建中间表),则以下内容应该有效
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; }
}
Run Code Online (Sandbox Code Playgroud)