Why doesn't EF update the FK column when no object state has been added?

I have an entity like this:

 public class Entity1
    {
        public short Id { get; set; }
        public int Entity2Id { get; set; }
        public virtual Entity2 Entity2 { get; set; }
    }

      

And you have a Many relation like this:

  this.HasRequired(m => m.Entity2)
            .WithMany()
            .HasForeignKey(m => m.Entity2Id)
            .WillCascadeOnDelete(false);

      

And here are the thoughts that I cannot understand:

For example, evertyhting works great if I first change the state of the object to Added

:

context.Entry(entity1).State = System.Data.EntityState.Added;
entity1.Entity2.Id = 541;

 // Since this line `entity1.Entity2Id` value is 0.
 context.Entry(entity1.Entity2).State = System.Data.EntityState.Unchanged;
 // But now everything is fine, because `entity1.Entity2Id` value is 541 also.

 context.Entry(entity1).State = System.Data.EntityState.Unchanged;

      

But I don't want to change the state to Added

, when I delete the first line, this exception happened:

A referential integrity constraint violation has occurred: the value property defining the referential constraints is incompatible between the principal and dependent objects in the relationship.

Beacuse, entit1.Entity2Id != entity1.Entity2.Id

.

And I don't want to manually change the value.

How can I get it to work without changing the state to Added

?

Update

I've researched this issue more. From this So question :

This is called the fixup property and is used by the auto-generated proxies. However, this is no longer the case with DbContext. According to this Connect issue, it is by design.

Hello, the DbContext template doesn't actually generate the classes to be used as change tracking proxies - just lazy loading proxies (which don't commit). We made this decision because change tracking proxies are complex and have many nuances that can be very confusing for developers. If you want the fix to happen before SaveChanges you can call myContext.ChangeTracker. DetectChanges . ~ EF Team

An alternative is to call DbContext.Entry (entity), which will synchronize the entity. This is described in this article: Relationships and Navigation Properties under "Synchronizing Changes Between FK and Navigation Properties"

+3


source to share





All Articles