Ef core 为名称为 *ID1 的导航 属性 创建附加列

Ef core Creating additional column for a navigation property with Name *ID1

我正在使用 Ef 核心代码优先生成数据库。但我不确定它为什么要创建一个带有 *ID1.

的新列

实体

public class Room : BaseEntity
{
    public string Name { get; set; }
    public string UniqueCode { get; set; }
    public int BranchId { get; set; }
    public virtual Branch Branch { get; set; }
    public CommonStatus Status { get; set; }
}

配置

public class RoomConfiguration : IEntityTypeConfiguration<Room>
{
    public void Configure(EntityTypeBuilder<Room> builder)
    {
        builder.Property(t => t.Name).IsRequired().HasMaxLength(10);
        builder.Property(t => t.UniqueCode).IsRequired().HasMaxLength(10);
        builder.HasIndex(p => p.Status);
        builder.HasOne(s => s.Branch)
            .WithMany()
            .HasForeignKey(e => e.BranchId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}

迁移

migrationBuilder.CreateTable(
                name: "Room",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(maxLength: 10, nullable: false),
                    UniqueCode = table.Column<string>(maxLength: 10, nullable: false),
                    BranchId = table.Column<int>(nullable: false),
                    Status = table.Column<int>(nullable: false),
                    BranchId1 = table.Column<int>(nullable: true)
                }

因为你可以设置迁移脚本实际上有我从未定义的 BranchId1。这也发生在某些实体中,但不是全部。我只想知道为什么会这样谢谢

您没有在 .WithMany() 上指定导航 属性。

WithMany():

Configures this as a one-to-many relationship. Note that calling this method with no parameters will explicitly configure this side of the relationship to use no navigation property, even if such a property exists on the entity type. If the navigation property is to be used, then it must be specified.

发生的事情是 EF 首先配置您与流利 API 建立的关系,然后它还为 List<Rooms> 创建关系。由于 BranchId 已用于您的流畅关系,因此它创建了第二个 FK,称为 BranchId1

所以你的关系应该是:

modelBuilder.Entity<Room>().HasOne(s => s.Branch)
    .WithMany(x => x.Rooms)
    .HasForeignKey(e => e.BranchId)
    .OnDelete(DeleteBehavior.Restrict);