c# - How to refresh an Entity Framework Core DBContext? -
when table updated party, db context in dotnet core still return old value, how can force db context refresh?
i've done research found people use reload
method, not available in ef core, force context refresh.
some other solution suggests dispose context after using, error saying db context created dependency injection , should not mess it.
you have detach
entity context, or implement own extension .reload()
here's .reload()
implementation. source: https://weblogs.asp.net/ricardoperes/implementing-missing-features-in-entity-framework-core
public static tentity reload<tentity>(this dbcontext context, tentity entity) tentity : class { return context.entry(entity).reload(); } public static tentity reload<tentity>(this entityentry<tentity> entry) tentity : class { if (entry.state == entitystate.detached) { return entry.entity; } var context = entry.context; var entity = entry.entity; var keyvalues = context.getentitykey(entity); entry.state = entitystate.detached; var newentity = context.set<tentity>().find(keyvalues); var newentry = context.entry(newentity); foreach (var prop in newentry.metadata.getproperties()) { prop.getsetter().setclrvalue(entity, prop.getgetter().getclrvalue(newentity)); } newentry.state = entitystate.detached; entry.state = entitystate.unchanged; return entry.entity; }
Comments
Post a Comment