是否可以在实体框架中将表FK链接到另外两个PK?

问题描述 投票:0回答:1

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

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

我正在使用ApiController将项目插入购物车,问题是当我插入ID为1的Box时,购物车中的FK将ID更新为1,但没有迹象表明它是项目还是框。

我试图在购物车表中为每个物品和箱子ID提供多个FK,但代码首先是在FK中给出有关空值的错误。我试过让它们可以为空但这在尝试连接表进行数据检索时会导致错误。

以下所示关系的最佳做法是什么?

enter image description here

购物车型号:

  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个回答
1
投票

为什么不将box视为单独的项目,因此您将有一个表而不是两个表。

例如。

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属性。

© www.soinside.com 2019 - 2024. All rights reserved.