2

I'm having issues retrieving navigation properties after an insert.

I'm saving data using this code, without setting the navigation properties that I do not want to change. For example :

var entity = new MyEntity 
              {
                FirstId = 1, 
                FirstObject = null
                SecondId = 1, 
                SecondObject = null
                //...data to update
              };
_context.Update(myEntity);
_context.SaveChanges();

Then if I try to access the navigation property it will be null (even if the main object is tracked after the savechanges). I tried to reload the data using:

_context.Entry(entity).State = EntityState.Detached;
entity = _context.Set<MyEntity>().Where(e => e.Id == entity.Id).First();

I've tried using reload too:

_context.Entry(entity).State = EntityState.Detached;
_context.Entry(entity).Reload();

Still, navigation properties are null.

I am using UseLazyLoadingProxies in context configuration. The only way to get the navigation property is to load it manually:

_context.Entry(entity).Reference(e=> e.FirstObject ).Load()

Is there a way to reload data from db (discarding all the cached data) after a SaveChanges()?

1 Answers1

3

Reload does not retrieve the related data (navigation properties). And lazy loading does not work since you are creating the entity instance with new operator, thus it is not proxied, which is the essential for lazy loading proxies.

Detaching and retrieving the entity for the database should work (and in my test it does work, not sure why you claim it doesn`t):

_context.Entry(entity).State = EntityState.Detached;
entity = _context.Set<MyEntity>().Where(e => e.Id == entity.Id).First();

But the better option is to create a proxied instance instead of new using one of the extension methods (either DbContext or DbSet<T>). The only drawback is that you lose object initializer syntax, but everything else will work. e.g.

var entity = _context.CreateProxy<MyEntity>(); // <--

entity.FirstId = 1; 
entity.SecondId = 1; 
//...data to update
_context.Update(entity);

_context.SaveChanges();

// verify it is working
var firstObject = entity.FirstObject;
var secondObject = entity.SecondObject;
Debug.Assert(firstObject != null && secondObject != null);

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • I worked like a charm, thank you! I don't know why reloading the data from the db does not work in my case...seems like ef keeps some sort of cache of the model. – Enrica Berardi Jul 16 '21 at 08:01