首页 > 解决方案 > 如何在 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。

标签: c#mysqldatabase.net-coreentity-framework-core

解决方案


你要去继承。EF TPT 中有两种类型,Table per Type(每种类型都有自己的表,它们共享主键)和 TPI Table per Inheritance(整个继承得到一个表,并且有一个区分类型的列)。EF core 只支持第二个。这意味着您的数据库架构需要更改为只有一个表用于此功能。

您可以做的另一件事是切换到组合而不是继承。因此,武器和盔甲将由物品和额外属性组成。

这是一篇可以帮助您了解细节的文章: https ://www.thinktecture.com/en/entity-framework-core/table-per-type-in​​heritance-support-part-1-code-first/


推荐阅读