[英]When using EF Fluent API to map my entities relationships, do I need to map on both entities involved?
I'm creating the entity relationships using Code First with EF Fluent API following the instructions from this tutorial to create the 1:n and m:n relationships in my model. 我将按照本教程中的说明,使用带有EF Fluent API的Code First创建实体关系,以在模型中创建1:n和m:n关系。
What I'm wondering and haven't found a response searching, is that if it's required to define the relationship on both ends of it. 我想知道但尚未找到响应搜索的是,是否需要在它的两端定义关系。
By that I mean, if I have an entity called User and Organization, there are two relationships involving these two entities as I described below: 我的意思是,如果我有一个名为“用户和组织”的实体,则有两个关系涉及这两个实体,如下所述:
With this in mind, I defined the relationships using Fluent API as follows: 考虑到这一点,我使用Fluent API定义了如下关系:
modelBuilder.Entity<Organization>().HasRequired(o => o.Owner).WithMany(u => u.OrganizationsOwned).WillCascadeOnDelete(false);
modelBuilder.Entity<User>().HasMany<Organization>(u => u.Organizations).WithMany(o => o.Users).Map(uo =>
{
uo.MapLeftKey("UserId");
uo.MapRightKey("OrganizationId");
uo.ToTable("OrganizationsUsers");
});
But are these definitions enough? 但是这些定义够吗? Or do I have to define the relationships on the other end of the entities too? 还是我也必须在实体的另一端定义关系? What I mean, do I need to add the following code? 我的意思是,我需要添加以下代码吗?
modelBuilder.Entity<User>().HasMany(u => u.OrganizationsOwned).WithRequired(o => o.Owner).WillCascadeOnDelete(false);
modelBuilder.Entity<Organization>().HasMany<User>(o => o.Users).WithMany(u => u.Organizations).Map(ou =>
{
ou.MapLeftKey("UserId");
ou.MapRightKey("OrganizationId");
ou.ToTable("OrganizationsUsers");
});
Yes, these definitions are enough. 是的,这些定义就足够了。 You are defining both sides of the relationship with the single statement: 您将使用单个语句定义关系的两侧:
.Entity<Organization>().HasRequired(o => o.Owner).WithMany(u => u.OrganizationsOwned)
The .HasRequired defines the 1 side, and the .WithMany defines the Many side. .HasRequired定义1面,.WithMany定义Many面。 There is only one relationship, but two sides. 只有一种关系,但是只有两种关系。 You can define the relationship from either side, but you do not have to define it from both. 您可以从任何一侧定义关系,但是不必从双方都定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.