我正在使用EF Core 2.0并与连接实体创建了多对多关系。当我添加新的迁移时,EF总是会创建一个完全愚蠢的附加索引/标识字段。这是我的加入实体:
public class Team_Member
{
public int TeamId { get; set; }
public Team Team { get; set; }
public int MemberId { get; set; }
public Member Member { get; set; }
public MemberTypeEnum MemberType { get; set; }
}
这是连接表的配置(以下是互联网上的几个例子):
public class Team_MemberConfig : IEntityTypeConfiguration<Team_Member>
{
public void Configure(EntityTypeBuilder<Team_Member> builder)
{
builder.ToTable("Team_Member");
builder.HasKey(tm => new { tm.TeamId, tm.MemberId });
builder.HasOne<Team>()
.WithMany(t => t.Team_Member)
.HasForeignKey(tm => tm.TeamId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<Member>()
.WithMany(m => m.Team_Member)
.HasForeignKey(tm => tm.MemberId)
.OnDelete(DeleteBehavior.Restrict);
}
}
对于每个外键列,迁移都会添加第二个:
columns: table => new
{
TeamId = table.Column<int>(nullable: false),
MemberId = table.Column<int>(nullable: false),
**MemberId1** = table.Column<int>(nullable: true),
MemberType = table.Column<int>(nullable: false),
**TeamId1** = table.Column<int>(nullable: true)
},
和两个完全相同的约束:
table.ForeignKey(
name: "FK_Team_Member_Member_MemberId",
column: x => x.MemberId,
principalTable: "Member",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Team_Member_Member_MemberId1",
column: x => x.MemberId1,
principalTable: "Member",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Team_Member_Team_TeamId",
column: x => x.TeamId,
principalTable: "Team",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Team_Member_Team_TeamId1",
column: x => x.TeamId1,
principalTable: "Team",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
我在这里做错了什么?
答案 0 :(得分:2)
只要您看到EF(Core)生成其他FK列,就会清楚地显示由于使用错误的流畅API重载而导致的未映射的引用或集合导航属性。所有相关的流畅API(HasOne
,HasMany
,WithOne
,WithMany
)都有重载和无导航属性。当相应的实体没有导航时,您必须使用第一个。您应该使用完全表示相应实体中是否存在导航属性的完全。如果不这样做会留下未映射的导航属性,EF会创建其他关系。
在您的情况下,两个差异(标记为A,B)介于:
之间public class Team_Member
{
public int TeamId { get; set; }
public Team Team { get; set; } // <-- A
public int MemberId { get; set; }
public Member Member { get; set; } // <-- B
public MemberTypeEnum MemberType { get; set; }
}
和
builder.HasOne<Team>() // <-- A
.WithMany(t => t.Team_Member)
.HasForeignKey(tm => tm.TeamId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<Member>() // <-- B
.WithMany(m => m.Team_Member)
.HasForeignKey(tm => tm.MemberId)
.OnDelete(DeleteBehavior.Restrict);
如前所述,只需将它们匹配:
builder.HasOne(tm => tm.Team) // <-- A
.WithMany(t => t.Team_Member)
.HasForeignKey(tm => tm.TeamId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(tm => tm.Member) // <-- B
.WithMany(m => m.Team_Member)
.HasForeignKey(tm => tm.MemberId)
.OnDelete(DeleteBehavior.Restrict);
问题已经消失。