【发布时间】:2016-05-24 16:41:11
【问题描述】:
我正在尝试使用联系人表创建用户。我不确定我的做法是否正确,因为添加了一个我没有声明的列。
实体:
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 列来自哪里?我的定义有问题吗?谢谢!
【问题讨论】:
-
您要建立 n:n 或 1:n 关系吗?从您的模型看来,您有 1 个用户和 n 个联系人,如果我没记错的话,这不是多对多而是一对多。
-
@HotTowelie 它是 1:n 到
Contact,然后是 n:1 到Contact.ContactUser。所以,User是 n:n 到 它自己。 -
可能相关:
User.Contacts不能同时是从User到其ContactUsers 的导航属性 和同时向另一方向移动的导航属性.其中一个应该从User实体中配置出来,另一个配置为无参数HasMany()。
标签: c# asp.net asp.net-core entity-framework-core