gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:08:34 25 4
gpt4 key购买 nike

我刚刚升级到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com