首页 > 解决方案 > 将扩展类存储在不同的表中

问题描述

我有一个包含[Key]字段的抽象超类。然后该类被 2 个不同的类扩展,它们共享这个 [Key] 字段,但也有自己的一些字段。

但问题是,当我DbSet<>为这 2 个扩展类创建 2 个对象时,它们被放入同一个表中,并且它们的字段被合并到该表中。所以在我的Context课堂上,我定义了这些:

DbSet<EmployeeAccount> EmployeeAccounts;
DbSet<PatientAccount> PatientAccounts;

我期待这些实体中的每一个都有一个单独的表,但我只有一个大表,并且 EmployeeAccounts 和 PatientAccounts 都可以使用该 1 个表(这使我在每一行中都有几列是空的)。

我猜这是因为 PatientAccount 和 EmployeeAccount 的超类具有相同的 [Key]。

抽象类非常简单,看起来像这样:

public abstract class UserAccount : Entity<int>
{
     [Key]
     public int Id { get; set; }
     public string Username { get; set; }
     public string Password { get; set; }
}

扩展类如下:

public class EmployeeAccount : UserAccount
{
     [ForeignKey("Employee")]
     public int EmployeeId { get; set; }
     public Employee Employee { get; set; }

     [Column(TypeName = "nvarchar(24)")]
     public EmployeeType EmployeeType { get; set; }
 }

public class PatientAccount : UserAccount
{
    [ForeignKey("Patient")]
    public int PatientId { get; set; }
    public Patient Patient { get; set; }

    public IEnumerable<FavoriteDoctor> FavouriteDoctors { get; set; }
}

我做错了什么,还是这是预期的行为?如果可以的话,有没有办法让我对 EF 说为这些实体创建 2 个单独的表,即使它们共享相同的 [Key] 字段和超类?

提前致谢。

标签: entity-framework-core

解决方案


推荐阅读