我正在尝试使用实体框架创建应用程序。
这是我想要做的(每个实体也有Id ):
在本例中,我想使用复合主键(PatientId + DiagnosisId
)。在Patient model类中有一个诊断集合:
public ICollection<Diagnosis> Diagnoses { get; set; }
public class Diagnosis
{
[Required]
[MaxLength(200)]
public String Type { get; set; }
public String Complications { get; set; }
public String Details { get; set; }
public Int32 DiagnosisId { get; set; }
public Patient Patient { get; set; }
public Int32 PatientId { get; set; }
}
同样在我定义的数据库上下文中
public DbSet<Diagnosis> Diagnoses { get; set; }
和
modelBuilder.Entity<Diagnosis>().HasKey(x => new { x.DiagnosisId, x.PatientId });
在OnModelCreating
方法中创建复合主键。
在一个ASP.NET MVC CRUD控制器中,我创建了Diagnosis
,每次DiagnosisId
都是相同的= 0。而且我不能将新数据粘贴到数据库中,因为它就像是重复的。这是我在Pastebin上的create post方法,如果它能有所帮助的话
发布于 2020-04-08 16:13:01
首先是父键:
modelBuilder.Entity<Diagnosis>().HasKey(x => new { x.PatientId, x.DiagnosisId });
因为你想要一个特定专利的所有诊断信息存储在一起。
并且您需要请求由数据库生成密钥。对于EF Core its:
modelBuilder.Entity<Diagnosis>().Property(r => r.DiagnosisId).ValueGeneratedOnAdd();
对于EF6,它是:
modelBuilder.Entity<Diagnosis>().Property(r => r.DiagnosisId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
https://stackoverflow.com/questions/61105090
复制