user1166905
user1166905

Reputation: 2622

Error in Entity Framework Saving with Child Entity

I have the following model:

public class Job
{
    [Key]
    public int JobID { get; set; }
    public string Status { get; set; }
    public DateTime JobDate { get; set; }
    public string JobTitle { get; set; }
    public int? Cleaner { get; set; }
    public int? Client { get; set; }
    public int EstTime { get; set; }

    public virtual Client ClientInfo { get; set; }
    public virtual Valeter ValeterInfo { get; set; }
}

This in OnModelCreating:

// Relationship Job -> Valeter
        modelBuilder.Entity<Job>()
            .HasOptional<Valeter>(u => u.ValeterInfo)
            .WithMany()
            .HasForeignKey(e => e.Cleaner);

(NOTE: it is using an existing database). When I try to perform the following:

if (ModelState.IsValid)
{
   db.Entry(job).State = EntityState.Modified;
   db.SaveChanges();
}

It generally works fine UNLESS I change the Cleaner value to something else and then I get the error:

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.

Upvotes: 0

Views: 233

Answers (1)

Slauma
Slauma

Reputation: 177133

This exception usually occurs if job.ValeterInfo != null and job.ValeterInfo.ValeterId != job.Cleaner. So, the simplest solution is to set the navigation property to null before you attach the job to the context:

if (ModelState.IsValid)
{
    job.ValeterInfo = null;
    db.Entry(job).State = EntityState.Modified;
    db.SaveChanges();
}

This looks a bit strange and like a hack. But the question is why job.ValeterInfo is NOT null when you post the data to the controller action. When you set the state of the job to Modified you are only updating the job's scalar properties (including Cleaner) but not any properties of job.ValeterInfo or any relationships. So, you don't need to send job.ValeterInfo properties to the server in the first place.

Anyway, you have an inconsistency: The FK job.Cleaner is changed but the related entity job.ValeterInfo (especially its primary key property ValeterId) is not. EF doesn't know which represents the correct relationship: The foreign key property value or the navigation property value? This ambiguity causes the exception.

Upvotes: 2

Related Questions