Error when editing an entity with EF Code First

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();

Answers


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();

Need Your Help