c# - Entity Framework Core - 外键 1(额外的外键列)

标签 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);
    });

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

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

modelBuilder.Entity<Voucher>().HasOne(x => x.Transaction).WithOne(x => x.Voucher).IsRequired(false);

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

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

最佳答案

如果您以两种方式绑定(bind)模型但忘记流畅地使用它,也可能会发生这种情况:

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) // <-- EDIT: Also use it like this, not .HasOne<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)
;

关于c# - Entity Framework Core - 外键 1(额外的外键列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46437206/

相关文章:

c# - EF5 : LINQ to Entities does not recognize the method System. 可空系统。十进制中位数

c# - EntitySet System.InvalidOperationException - "the entity type is not part of the model for the current context"

entity-framework - EF 5 模型第一部分类自定义构造函数如何?

c# - Visual Studio 从一般开发设置更改

c# - Entity Framework 6 中的直接导航属性

c# - Dapper 和 Varbinary(max) 流参数

entity-framework - 如何在不使用导航属性的情况下在 codefirst 中设置外键关系?

c# - 在 Code First Entity Framework 中为数据库中的现有列添加属性到模型

c# - 在 UWP 应用程序中检测 sleep 事件或唤醒事件

C#/Outlook - 检索特定的全局联系人