![](/img/trans.png)
[英]EF Core 5.0 - Updating many-to-many entities in ASP.NET Core Web API
[英]ASP.NET Core EF Many to Many referencing table
我正在尝试创建具有联系人表的用户。 我不确定我是否以正确的方式进行操作,因为添加了未声明的列。
实体:
public class User
{
public int Id { get; set; }
public bool IsAvailable { get; set; }
public List<Contact> Contacts { get; set; }
}
public class Contact
{
public int UserId { get; set; }
public int ContactUserId { get; set; }
public User User { get; set; }
public User ContactUser { get; set; }
}
映射:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>()
.HasKey(x => new { x.UserId, x.ContactUserId });
modelBuilder.Entity<Contact>()
.HasOne(x => x.User)
.WithMany(x => x.Contacts)
.HasForeignKey(x => x.UserId);
modelBuilder.Entity<Contact>()
.HasOne(x => x.ContactUser)
.WithMany(x => x.Contacts)
.HasForeignKey(x => x.ContactUserId);
}
结果:
migrationBuilder.CreateTable(
name: "Contact",
columns: table => new
{
UserId = table.Column<int>(nullable: false),
ContactUserId = table.Column<int>(nullable: false),
UserId1 = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Contact", x => new { x.UserId, x.ContactUserId });
table.ForeignKey(
name: "FK_Contact_User_ContactUserId",
column: x => x.ContactUserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Contact_User_UserId1",
column: x => x.UserId1,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
真正的问题:
联系人列UserId1来自何处? 我的定义有问题吗? 谢谢!
之所以在联系人表上添加一个额外的UserId1 ,是因为您将Contact对象上User和ContactUser关联的另一端都指定为User对象上的Contacts ,这是不正确的。 结果,EF将忽略它,并为User对象上的Contacts创建另一个关联,并将其映射到Contact表的UserId1列。
解决此问题的一种方法是在User对象上创建另一个联系人列表并进行相应映射:
public class User
{
public int Id { get; set; }
public bool IsAvailable { get; set; }
public List<Contact> Contacts { get; set; }
public List<Contact> ContactUsers { get; set; }
}
modelBuilder.Entity<Contact>()
.HasOne(x => x.User)
.WithMany(x => x.Contacts)
.HasForeignKey(x => x.UserId);
modelBuilder.Entity<Contact>()
.HasOne(x => x.ContactUser)
.WithMany(x => x.ContactUsers)
.HasForeignKey(x => x.ContactUserId)
.OnDelete(DeleteBehavior.Restrict);
产生所需的模式:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.