首页 > 解决方案 > 如何使用 EntityFramework 将相关实体添加到数据库

问题描述

我正在尝试将购物车添加到数据库但不知道如何添加相关Entities 我的相关表是 ( carts, products, productoptions, options)

这是数据库图

如何同时添加或更新这些表?以及如何将外键设置为相关Tables

谢谢...

标签: c#sqlsql-serverentity-frameworkasp.net-web-api

解决方案


您将为每个表创建模型(见下文)

然后,如果您只添加一个孩子,则必须在填充的外键属性的情况下添加它

var test = childObj { parentPropertyId = parentPropertyIdValue}

如果您将父母和孩子一起添加,您只需添加,实体 mework 将负责这一点。例如:

var test = new parentObj {
someProperty = someValue,
childProperty = new childObj{
//here will not have to populate the parentPropertyId
    }

}

请参阅上表的示例模型

使用 [Key] 属性指定您的主键

使用相关实体属性上方的 [ForeignKey] 属性来指定要用作外键的属性

使用 ICollection 访问对象的子对象

 public class Carts
{
    [Key]
    public int Id { get; set; }
    public int Userid { get; set; }
    public DateTime CreatedDate { get; set; }
    public ICollection<Products> Products { get; set; }
}

public class Products
{
    [Key]
    public int Id { get; set; }
    public string SerialNumber { get; set; }
    public string StockCode { get; set; }
    public int CartId { get; set; }
    public int Quantity { get; set; }

    [ForeignKey(nameof(CartId))]
    public Carts Cart { get; set; }

}

public class ProductOptions
{
    [Key]
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int OptionId { get; set; }

    [ForeignKey(nameof(ProductId))]
    public Products Products { get; set; }

    [ForeignKey(nameof(OptionId))]
    public  Options Options { get; set; }
}

public class Options
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public int ParentId { get; set; }
    public int GrandParentId { get; set; }
}

推荐阅读