Unfortunately although EntityEntry
has Reload
method, there is no such method for ReferenceEntry
and CollectionEntry
(or in general, for NavigationEntry
which the base of the previous two). And Reload
methods refreshes just the primitive properties, so it can't be used to refresh the navigation properties.
Fortunately it's not that hard to create a custom one. It needs to detach (or reload?) all the current collection items, set IsLoaded
to false
and CurrentValue
to null
before calling Load
.
Something like this (put it in a static class of your choice and add the necessary using
s):
public static void Reload(this CollectionEntry source)
{
if (source.CurrentValue != null)
{
foreach (var item in source.CurrentValue)
source.EntityEntry.Context.Entry(item).State = EntityState.Detached;
source.CurrentValue = null;
}
source.IsLoaded = false;
source.Load();
}
so you can use the desired
_dbContext.Entry(blog).Collection(b => b.Posts).Reload();