簡體   English   中英

ASP.NET Core EF多對多引用表

[英]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對象上UserContactUser關聯的另一端都指定為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM