c# - 如何使用 EntityFramework 将相关实体添加到数据库
问题描述
我正在尝试将购物车添加到数据库但不知道如何添加相关Entities
我的相关表是 ( carts
, products
, productoptions
, options
)
如何同时添加或更新这些表?以及如何将外键设置为相关Tables
谢谢...
解决方案
您将为每个表创建模型(见下文)
然后,如果您只添加一个孩子,则必须在填充的外键属性的情况下添加它
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; }
}
推荐阅读
- github - 在 wiki 编辑上触发 Github 操作?
- angular - 在nebular ui nbwindow中从子组件获取数据到父组件
- swift - SwiftUI 不同的子对齐方式和 GeometryReader
- javascript - 从 main.js 外包功能
- powershell - PowerShell 查找域中的计算机,用户已登录
- mysql - Qt 5.14.2下编译MySql插件
- delete-file - 如何在 Figma 中恢复已删除的帧?
- java - 字段列表中的列不明确
- jasper-reports - 如何在 jasper 报告中声明参数
- javascript - 将两个画布元素放在一起