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()?
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. eg
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.