【问题标题】:How do I store a list of objects in field using Entity Framework 6如何使用 Entity Framework 6 在字段中存储对象列表
【发布时间】:2019-03-20 20:16:35
【问题描述】:

我正在尝试为电子商务解决方案编写支付流程,我想收集购物车中的所有产品,然后在 List<OrderProducts> 中,然后将该列表存储到对象 Order 中。

POCO 类如下:

Order.cs

public class Order
{
    public int Id { get; set; }
    public double TotalAmount { get; set; }
    public IdentityUser UserAccount { get; set; }
    public virtual ICollection<OrderProduct> OrderProduct { get; set; }
    public DateTime OrderDate { get; set; }
    public bool IsComplete { get; set; }
}

OrderProduct.cs

public class OrderProduct
{
    public int Id { get; set; }
    public Order Order { get; set; }
    public Product Product { get; set; }
    public int Quantity { get; set; }
}

在运行迁移和更新数据库后,Order 表中的 OrderProduct 列似乎甚至没有显示在数据库设计中。

有人可以根据上述情况提供帮助或提供更好的解决方案吗?

【问题讨论】:

  • 我认为您需要展示更多关于如何在 C# 中配置表关系并将架构推送到 Db 的代码。
  • @pmcilreavy 你指的是 DbContext 类吗?我还没有对表关系进行任何配置。如果您的意思是ProductIdentityUser,请暂时忽略它们

标签: c# asp.net-core entity-framework-6 entity-framework-migrations


【解决方案1】:

更改您的 OrderProduct 类,然后重新生成迁移:

public class OrderProduct
{
    [Key]
    public int Id { get; set; }
    public int OrderId {get;set;}
    [ForeignKey(nameof(OrderId))]
    public virtual Order Order { get; set; }
    public Product Product { get; set; }
    public int Quantity { get; set; }
}

【讨论】:

  • 我收到此错误To change the IDENTITY property of a column, the column needs to be dropped and recreated.,在我的其他表中,我不必为键指定属性。 EF 自动将 Id 识别为 PK 并为对象存储 FK
猜你喜欢
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 2015-11-09
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2015-09-17
相关资源
最近更新 更多