【问题标题】:Is it possible to link a table FK to 2 other PK in entity framework?是否可以将表 FK 链接到实体框架中的 2 个其他 PK?
【发布时间】:2019-03-07 12:21:20
【问题描述】:

我有一个购物车,可以从两个单独的桌子上接收商品。

一个表包含单个项目,另一个包含多个项目的框。

我正在使用 ApiController 将项目插入购物车,问题是当我插入 ID 为 1 的 Box 时,Cart 中的 FK 会将 ID 更新为 1,但没有指示它是 Item 还是 Box .

我尝试在购物车表中为每个项目和框 ID 设置多个 FK,但代码首先给出了有关 FK 中的空值的错误。我已尝试将它们设为可为空,但这会在尝试加入表以进行数据检索时导致错误。

下面显示的关系的最佳做法是什么?

购物车型号:

  public class Cart
  {
    [Key]
    public int RecordID { get; set; }
    public string CartID { get; set; }
    public int ItemID { get; set; }
    public int BoxID { get; set; }
    public int Qty { get; set; }
    public System.DateTime DateCreated { get; set; }

    public Item Item{ get; set; }
    public Box Box { get; set; }

    public string UserID { get; set; }
    public ApplicationUser User { get; set; }
}

【问题讨论】:

    标签: entity-framework model-view-controller ef-code-first-mapping


    【解决方案1】:

    您为什么不将盒子视为一个单独的项目,结果您将拥有一张桌子而不是两张桌子。

    例如。

    public class Cart
    {
        [Key]
        public int RecordID { get; set; }
        public string CartID { get; set; }
        public int ItemID { get; set; }
        public int Qty { get; set; }
        public System.DateTime DateCreated { get; set; }
    
        public Item Item{ get; set; }
    
        public string UserID { get; set; }
        public ApplicationUser User { get; set; }
    }
    public class Item
    {
        [Key]
        public int ItemID { get; set; }
        .
        .
        .
    }
    

    在这种情况下,您将能够为单个项目和盒子项目分配不同的 ID。

    您也可以使用 Qty 属性以防盒子中的物品相同。

    【讨论】:

    • 我正在尝试将 Box 和 Items 保存在单独的表格中,以使将来的分析更容易。因为 1 个盒子可能包含多个不同的项目。例如 BoxID1 包含:ItemID1 x5、ItemID2 x1、ItemID3 x1 等
    • 然后将ICollection<Item> 添加到您的项目实体。
    • 在这种情况下,我认为您将需要使用 Table per Type (TPT) 继承方法。例如添加一个将抽象的父类,并且 Item 和 Box 类都将从父类继承。使用 TPT 方法可以解决这个问题。有关更多详细信息,请参阅本文。 entityframework.net/tpt
    猜你喜欢
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多