簡體   English   中英

身份新表外鍵AspNetUsers

[英]Identity new table foreign key to AspNetUsers

我正在MVC Identity下創建一個新表(我們稱之為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)。

如果我正確地假設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 此配置中子類的所有屬性都必須為空,因為從邏輯上講,在保存Patient時無法為Doctor提供所需的值。 但是,這僅在數據庫級別強制執行。 您仍然可以自由驗證表單中的輸入(例如,根據需要),即使不需要輸入的表列也是如此。

也就是說,您還可以使用其他策略。 在這種情況下,最合適的替代方法是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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM