Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core 5 Reload issue

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()?

like image 622
Enrica Berardi Avatar asked Jun 27 '26 01:06

Enrica Berardi


1 Answers

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);

like image 185
Ivan Stoev Avatar answered Jun 28 '26 14:06

Ivan Stoev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!