尝试设置外键配置时遇到问题。
具有外键属性{'OrderId':int}的从'OrderStatus.Order'到'Order.OrderStatuses'的关系不能针对主键{'Id':int,'TransactionId':int},因为它不是兼容。为此关系配置一个主键或一组兼容的外键属性。
System.Exception; System.InvalidOperationException
需要加入Order.OrderId
和OrderStatus.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);
}