我正在开发一个简单的web应用程序,医生正在为病人添加多个处方记录,并将在进行处方时选择多种药物。因此,一个病人有多个处方,一个处方有多个选择的药物。我使用了另一个表的病人记录来报告目的/规范化透视图,在这里我引用了patientID和PrescriptionID。
下面是病人的模型,处方和药物,PatientRecord表。




在运行迁移时,我会得到以下错误:
错误号:1769,状态:1,类别:16 引用表'FK_Drugs_Prescriptions_PrescriptionID‘中的外键'PrescriptionID’引用无效列‘PrescriptionID’。
我对微软网站上的一对多关系的解释感到困惑。
有人能帮我吗?
发布于 2020-04-17 09:38:47
配置EF核心中的关系有两种方法
HasOne或HasMany标识正在开始配置的实体类型上的导航属性。HasOne/WithOne用于引用导航属性,HasMany/WithMany用于集合导航属性。根据你的截图和本杰明的建议,你可以像下面这样配置模型
病人处方->一对多关系处方-药物->多对多关系
public class Prescription
{
public int PrescriptionId { get; set; }
[Required]
public string Description { get; set; }
[Required]
public DateTime PrescriptionDate { get; set; }
public int PatientId { get; set; }
public Patient Patient { get; set; }
public ICollection<DrugPrescription> DrugPrescriptions { get; set; }
}
public class Drug
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int CurrentStock { get; set; }
public int DrugCost { get; set; }
public string Description { get; set; }
public ICollection<DrugPrescription> DrugPrescriptions { get; set; }
}
//represent a many-to-many relationship by including an entity class for
//the join table and mapping two separate one-to-many relationships.
public class DrugPrescription
{
public int DrugId { get; set; }
public Drug Drug { get; set; }
public int PrescriptionId { get; set; }
public Prescription Prescription { get; set; }
}
//DbContext
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{}
public DbSet<Patient> Patient { get;set; }
public DbSet<Drug> Drug { get;set; }
public DbSet<Prescription> Prescription { get;set; }
public DbSet<PatientRecord> PatientRecord { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
#region Drug-Prescription Many-to-Many
builder.Entity<DrugPrescription>()
.HasKey(dp => new { dp.DrugId, dp.PrescriptionId });
builder.Entity<DrugPrescription>()
.HasOne(dp => dp.Prescription)
.WithMany(p => p.DrugPrescriptions)
.HasForeignKey(dp => dp.PrescriptionId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<DrugPrescription>()
.HasOne(dp => dp.Drug)
.WithMany(d => d.DrugPrescriptions)
.HasForeignKey(dp => dp.DrugId)
.OnDelete(DeleteBehavior.Restrict);
#endregion
}
}发布于 2020-04-16 13:29:54
有几件事情看上去不太对劲。也许如果你把它们清理干净,你就会发现错误在哪里。
首先,我对您的PatientRecord类感到有点困惑。它用PatientRecordId标识自己,并映射到Patient,但它不添加任何其他信息,那么它是干什么用的呢?如果您不打算向该类添加任何内容,我认为您可以将其从模型中删除。
其次,Prescription类映射到Drugs的集合。太完美了因为你和他们之间有一对多的关系.那么为什么它也有一个整数DrugId属性呢?除非您希望Prescription类引用单个Drug的Id以及Drugs的集合,否则我认为您应该删除它。它可能会混淆实体框架,而不会给您任何价值。
第三,Drug类映射到一个Prescription (通过它的属性Prescription和PrescriptionId),但是为什么呢?一种药物可能会出现在多种处方上,因为它可以给许多人开,也可以给同一个人开好几次。所以我想你也想把它去掉,代之以多到多的关系。
最后,如果您想在Prescription和Drug之间建立多到多的关系(我认为您会这样做),您可能需要添加一个带有Drug属性和Prescription属性的DrugPrescription类来创建这种多到多的映射。
我认为如果你这样做,你会离你的目标很近,你的错误信息可能会消失。
https://stackoverflow.com/questions/61249234
复制相似问题