0

I use Entity Framework 6 with SQLite and code first. I have a problem with the update of objects.

I have an "Record" object

class Record {

  public long Id;
  public long StatusId

  public virtual Statut Status;
}

And so a "Status" object.

I create a Record object like that

var newRecord = context.Records.Create();

While I did not add it in the context, the Status property is null.

context.Records.Add(newRecord);

Now, I have a Status object in Status navigation property (The status object with id = 0).

But if I change StatusId with 1 for example (this status id exist), the Status property is not updated.

Entity framework should not detect this kind of change with dynamic proxies?

Thanks,

sbou
  • 213
  • 2
  • 12
  • What do you mean by "default Status"? If that's a non-null `Status` object, how does it get there if you didn't set `Status` nor `StatusId`? – Gert Arnold Oct 29 '14 at 13:16
  • StatusId is not nullable so by default its value is 0. And in my database I have a status object with 0 as Id. – sbou Oct 29 '14 at 13:20

1 Answers1

1

The behavior you observe is caused by Entity Framework's relationship fixup mechanism, a process that's triggered by many EF methods and that takes care of consistency of foreign key values and references (among others).

Relationship fixup is triggered by a pretty large number of methods, but DbSet.Create() is not one of them. So here's what happens:

var newRecord = context.Records.Create();

A new Record is created, having StatusId = 0. No relationship fixup.

context.Records.Add(newRecord);

The new record is attached to the context. Now EF does execute relationship fixup. If you monitor SQL, you will see that a Status record is fetched from the database.

newRecord.StatusId = 1;

No EF method is executed: no relationship fixup, the Status object is still the one with Id = 0.

What you can do now to get the right Status record into newRecord is either execute one of the methods that trigger relationship fixup, or call context.ChangeTracker.DetectChanges().

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • Thanks for your answer. Calling DetectChanges seems heavy. Why proxies don't make this work in setter ? – sbou Oct 29 '14 at 13:54
  • Because in most cases you don't need this. Recommended way to work with EF is create context - do stuff - save - dispose context. And then, `StatusId` is not overridden, so a proxy can't do anything with its setter. – Gert Arnold Oct 29 '14 at 14:01
  • When I read documentation at http://msdn.microsoft.com/en-us/data/jj713564.aspx in "Synchronizing the changeds between ths FKs and Navigation properties" I understand that Entity framework should make it for POCO entities with proxies. – sbou Oct 29 '14 at 14:04
  • Well, it's not entirely correct what they say there. If you change a primitive property like `StatusId` there is *no way* that DetectChanges can be triggered. – Gert Arnold Oct 29 '14 at 14:08