EF核心外键配置

时间:2020-01-03 11:14:54

标签: asp.net-core fluent ef-core-2.0

尝试设置外键配置时遇到问题。

具有外键属性{'OrderId':int}的从'OrderStatus.Order'到'Order.OrderStatuses'的关系不能针对主键{'Id':int,'TransactionId':int},因为它不是兼容。为此关系配置一个主键或一组兼容的外键属性。
System.Exception; System.InvalidOperationException

需要加入Order.OrderIdOrderStatus.TransactionId

模型类:

public class Order
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public ICollection<OrderStatus> OrderStatuses { get; set; }
}

public class OrderStatus
{
    public int Id { get; set; }
    public int TransactionId { get; set; }
    public string Status { get; set; }
    public DateTime Date { get; set; }
}

上下文配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
                .ToTable("OrdersTable")
                .HasKey(o => new { o.OrderId, o.CustomerId });

    modelBuilder.Entity<Order>()
                .HasMany(o => o.OrderStatuses)
                .WithOne(o => o.Order)
                .HasForeignKey(o => o.OrderId);

    modelBuilder.Entity<OrderStatus>()
                .ToTable("OrderStatusTable")
                .HasKey(os => os.TransactionId);
}

0 个答案:

没有答案