Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What triggers Entity Framework to fix up a navigation property?

I couldn't find good documentation on just exactly what makes Entity Framework decide to look up the correct related object when the foreign key is set.

I'm using lazy loading (but not change tracking) proxies. Setting the foreign key and then getting the navigation property value returns null, even when the related navigation object is already loaded and sitting in the DbContext.

Calling DetectChanges works but seems heavy. Is there any other way to clue in Entity Framework to do fixup?

like image 414
jnm2 Avatar asked Oct 02 '22 02:10

jnm2


1 Answers

You're right. DetectChanges is the method that triggers relationship fix-up. If you want relationship fix-up to happen for whatever reason, you call DetectChanges.

But DetectChanges is also called by EF itself when you execute the following methods:

  • DbSet.Add
  • DbSet.Find
  • DbSet.Remove
  • DbSet.Local
  • DbContext.SaveChanges
  • DbSet.Attach
  • DbContext.GetValidationErrors
  • DbContext.Entry
  • DbChangeTracker.Entries
  • Running any LINQ query against a DbSet

(From Lerman & Miller's book DbContext, p. 60).

As you see, almost anything you will do with EF after setting the foreign key value will call DetectChanges, so if you've got other useful stuff to do afterwards, do these things first and save one DetectChanges call.

like image 167
Gert Arnold Avatar answered Oct 10 '22 01:10

Gert Arnold