实体框架核心 - 外键 1(额外外键列)

Sel*_*rio 5 c# entity-framework ef-model-first

我刚刚升级到 Entity Framework Core 2,现在我遇到了一个额外的列存在问题并且有一个唯一的键,即使它不在我的模型中并且没有在其他任何地方定义。

指数:

migrationBuilder.CreateTable(
    name: "Vouchers",
    columns: table => new
    {
        Id = table.Column<int>(nullable: false)
            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
        Code = table.Column<Guid>(nullable: false),
        IsClaimed = table.Column<bool>(nullable: false),
        LastModified = table.Column<DateTime>(nullable: false),
        NumberOfUnits = table.Column<int>(nullable: false),
        TransactionId = table.Column<int>(nullable: false),
        TransactionId1 = table.Column<int>(nullable: true) // why is this here?
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_Vouchers", x => x.Id);
        table.ForeignKey(
            name: "FK_Vouchers_Transactions_TransactionId1",
            column: x => x.TransactionId1,
            principalTable: "Transactions",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    });
Run Code Online (Sandbox Code Playgroud)

TransactionId1 不在模型中:

public class Voucher : IAutoLastModified
{
    public int Id { get; set; }
    public DateTime LastModified { get; set; }

    public int TransactionId { get; set; }
    public Transaction Transaction { get; set; }

    public int NumberOfUnits { get; set; }
    public Guid Code { get; set; }
    public bool IsClaimed { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我是否错误地定义了外键?

modelBuilder.Entity<Voucher>().HasOne(x => x.Transaction).WithOne(x => x.Voucher).IsRequired(false);
Run Code Online (Sandbox Code Playgroud)

我的应用程序失败,因为 TransactionId1 始终为空并且具有我无法删除的唯一约束。

为什么 EF 为此表创建了一个额外的列?

Sel*_*rio 5

好的,所以我想出了问题所在(对于犯了同样错误的人,将问题保留在这里)。

我将关系标记为可选,但该列是一个int而不是,int?因此 EF 决定在幕后添加它自己的列。

修复此问题后,我必须重新创建数据库 - 由于现有数据,迁移未成功完成。


小智 5

如果您以两种方式定义模型,但忘记在 fluent 中使用它,也可能会发生这种情况:

public class Customer
{
    public Guid Id { get; set; }
    public List<Order> Orders {get; set;}
}

public class Order
{
    public Guid Id { get; set; }

    public Guid CustomerId { get; set; }
    public Guid Customer { get; set; }
}

// AppDbContext
builder.Entity<Order>()
     .HasOne(x => x.Customer)
     .WithMany() //WRONG -> should be .WithMany(x => x.Orders) OR modify the model to not define the collection at the customer entity
     .HasForeignKey(x => x.CustomerId)
     .OnDelete(DeleteBehavior.SetNull)
;
Run Code Online (Sandbox Code Playgroud)