![](/img/trans.png)
[英]ASP.NET MVC 5 Core Identity CompanyID foreign key on dbo.AspNetUsers table
[英]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)。
如果我正确地假设Patient
和Doctor
实际上都是“用户”,那么您实际上应该从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采用单表继承,因此在此配置中,您实际上不会最终获得Doctor
和Patient
单独表。 而是将两者的所有属性都添加到AspNetUsers
。 在大多数情况下,这不是问题。 唯一有问题的时间是,您是否需要只针对一个子类的属性,例如Doctor
。 此配置中子类的所有属性都必须为空,因为从逻辑上讲,在保存Patient
时无法为Doctor
提供所需的值。 但是,这仅在数据库级别强制执行。 您仍然可以自由验证表单中的输入(例如,根据需要),即使不需要输入的表列也是如此。
也就是说,您还可以使用其他策略。 在这种情况下,最合适的替代方法是TPT或Table-Per-Type。 在这里,您可以获得每种离散类型的表格ApplicationUser
, Doctor,
和Patient
。 然后,在子类( Doctor
和Patient
)上,将外键添加到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.