ASP.NET Core EF多對多引用表

asp.net asp.net-core c# entity-framework-core

我正在嘗試使用聯繫人表創建用戶。我不確定我是否以正確的方式進行,因為添加了一個我沒有聲明的列。

實體:

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對像上的聯繫人 ,這是不正確的。因此,EF忽略它並為User對像上的Contacts創建另一個關聯,並將其映射到Contact表上的UserId1列。

解決此問題的一種方法是在User對像上創建另一個Contacts列表並相應地映射它:

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);


這產生了所需的模式:

在此處輸入圖像描述



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow