c# - 如何在 C# 中使用一个外键将两个不同的表引用到一个公用表
问题描述
我有三个类,物品,盔甲和武器。
ITEM 是具有通用属性的父类,ARMOR 和 WEAPON 是我要链接到项目类的特定属性。
这是数据库架构:
一个项目是盔甲或武器,当我查询时,我想要属于项目和特定类的所有属性。
public class Item
{
public Guid Id { get; set; }
public bool Consumable { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public float Price { get; set; }
public float Weight { get; set; }
}
public class Armor
{
public Guid Id { get; set; }
public string ArmorClass { get; set; }
public ArmorType ArmorType { get; set; }
public bool Stealth { get; set; }
public int Strength { get; set; }
}
public class Weapon
{
public Guid Id { get; set; }
public int Damage { get; set; }
public WeaponType WeaponType { get; set; }
public List<string> Properties { get; set; }
}
我在如何链接这些表、在哪里写什么属性以及类似的东西时遇到了麻烦。
这个想法是使用 EF Core。
解决方案
你要去继承。EF TPT 中有两种类型,Table per Type(每种类型都有自己的表,它们共享主键)和 TPI Table per Inheritance(整个继承得到一个表,并且有一个区分类型的列)。EF core 只支持第二个。这意味着您的数据库架构需要更改为只有一个表用于此功能。
您可以做的另一件事是切换到组合而不是继承。因此,武器和盔甲将由物品和额外属性组成。
这是一篇可以帮助您了解细节的文章: https ://www.thinktecture.com/en/entity-framework-core/table-per-type-inheritance-support-part-1-code-first/
推荐阅读
- javascript - 如何使用 jquery 从列表中获取 ul li 的值
- python-3.x - 在 ubuntu 20 上为 python-3.8 创建 virtualenv 的盐状态
- python - 并行调用 xarray save_mfdataset() 或 to_netcdf() 时锁定
- javascript - 如何删除类中的事件侦听器?
- jmeter - 通过 Jemeter 使用参数化命令运行 Executable 的多次执行
- java - 有人能解释一下为什么只有字符串 s4 的打印结果是 10bab 吗?
- amazon-web-services - 如何从我的步骤函数工作流中调用动态活动?
- javascript - 如何从对象中获取名称并将其分配给新创建的元素?
- mysql - AWS Athena 查询仅获取数组中的一个对象
- mysql - 反向累积和 - MySQL