[英]EF Cannot insert explicit value for identity column in table 'PATIENT DONOR' when IDENTITY_INSERT is set to OFF
i am working using EF and I have a table that has an identity property and i tried a lot of solutions but i still get that error. 我正在使用EF,并且我有一个具有身份属性的表,我尝试了很多解决方案,但仍然遇到该错误。 i defined the property in the class as : 我在类中定义该属性为:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int PATIENTDONORID { get; set; }
and i still get that error and i made the identity option is on in OnModelCreating and i also get the same error 而且我仍然收到该错误,并且我在OnModelCreating中启用了identity选项,并且我也遇到了相同的错误
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// throw new UnintentionalCodeFirstException();
modelBuilder.Entity<PATIENT_DONOR>().Property(x => x.PATIENTDONORID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
this is the code that makes insertion and save changes in database: 这是进行插入并将更改保存到数据库中的代码:
foreach (var item in patient.DONORS)
{
if (item.Checked)
{
db.PATIENT_DONOR.Add(new PATIENT_DONOR() { PATIENT_ID = patient.PATIENT_ID, DONOR_ID = item.ID});
}
}
// db.Entry(patient).State = EntityState.Modified;
db.SaveChanges();
What should i do ? 我该怎么办 ?
It is working Correctly now . 现在它可以正常工作。 I realized that After any change in dB I must remove and redrag tables in model. 我意识到,在dB发生任何变化之后,我必须删除并重新拖动模型中的表。 and there is no problems in the code itself 而且代码本身没有问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.