将新表外键标识为AspNetUsers

时间:2016-05-26 16:14:16

标签: c# asp.net-mvc asp.net-mvc-5 asp.net-identity

我正在MVC身份下创建一个新表(我们称之为Chart),它由2列(PatientId和DoctorId)组成,它们将引用回AspNetUsers的Id列。新表也将拥有自己的PK。以下是 IdentityModels 类。

public class ApplicationUser : IdentityUser 
{
  public virtual Chart Chart { get; set; }     
  ...
}

public class Chart 
{
   [Key]
   public int Id { get; set; } 

   //How to FK the following two params?
   public string PatientId { get; set; }
   public string DoctorId { get; set; }

   public virtual ApplicationUser User { get; set; } // navigation property    
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
{
    public ApplicationDbContext()
          : base("DefaultConnection", throwIfV1Schema: false) {
}

public System.Data.Entity.DbSet<Chart> Chart { get; set; }

public static ApplicationDbContext Create()
{
   return new ApplicationDbContext();
}

我可以知道如何将PatientId和DoctorId引用回AspNetUsers表的Id列吗?

这将是一对多的关系(一个DoctorId可以有许多PatientId,但一个PatientId只能附加到一个DoctorId)。

1 个答案:

答案 0 :(得分:2)

如果我认为PatientDoctor实际上都是“用户”,那么你应该从ApplicationUser继承它们。

public class Patient : ApplicationUser
{
    // patient-specific properties

    [ForeignKey("Doctor")]
    public string DoctorId { get; set; } // IdentityUser's PK is string by default
    public virtual Doctor Doctor { get; set; }
}

public class Doctor : ApplicationUser
{
    // doctor-specific properties

    public virtual ICollection<Patient> Patients { get; set; }
}

默认情况下,Entity Framework使用单表继承,因此在此配置中,您实际上不会为DoctorPatient添加单独的表。相反,两者的所有属性都将添加到AspNetUsers。在大多数情况下,这不是问题。唯一可能有问题的是,如果您需要特定于一个子类的属性,例如Doctor。此配置中子类的所有属性都必须是可为空的,因为在保存Doctor时,逻辑上无法为Patient提供所需的值。但是,这仅在数据库级别强制执行。您仍然可以自由地验证表单中的输入,例如,根据需要,即使支持它的表列不是。

也就是说,您可以使用其他策略。在这种情况下,最合适的替代方案是TPT或Table-Per-Type。在这里,您可以获得每个离散类型的表格ApplicationUserDoctor,Patient。然后,在子类(DoctorPatient)上将外键添加到ApplicationUser。正是ApplicationUser实例保存了实体的真实“id”。要使用TPT,就像为每个类添加Table属性一样简单:

[Table("Doctors")]
public class Doctor : ApplicationUser

[Table("Patients")]
public class Patient : ApplicationUser

<强>更新

关于Chart,使用此设置,您的实现将如下所示:

public class Chart 
{
    [Key]
    public int Id { get; set; } 

    [ForeignKey("Patient")]
    public string PatientId { get; set; }
    public virtual Patient Patient { get; set; }

    [ForeignKey("Doctor")]
    public string DoctorId { get; set; }
    public virtual Doctor Doctor { get; set; }
}
相关问题