0
votes

I get this error when trying to Edit an entity with EF Code first:

A referential integrity constraint violation occurred: the property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.

My Entity is a Producer that has relation with State. my code for edit is like below:

Producer producer = this.DataContext as Producer;
context.Producers.Attach(producer);
context.Entry(producer).State = EntityState.Modified;
context.SaveChanges();
1
What are the other entities referenced by Producer? - Eranga
@Eranga Producer has an State (optional) and also has many Product. but i find a solution and answered my question. - Mohammad Zare

1 Answers

0
votes

I Find a solution. I Use the below code and it works fine but i'm still unsure about is it the best way or not.

Producer producer = this.DataContext as Producer;
Producer p = context.Producers.Find(producer.Id);
context.Entry(p).CurrentValues.SetValues(producer);
context.SaveChanges();