Search code examples
c#entity-framework-coreef-core-2.2

How to reload collection in EF Core 2.x?


I know there is a Load method.

_dbContext.Entry(blog).Collection(b => b.Posts).Load()

But I'm try to handle concurrency conflicts, I've been add a post into blog.Posts. if call Load, it do not clear the blog.Posts, just append the existing Posts to it.

I had try:

blog.Posts = null;
_dbContext.Entry(blog).Collection(b => b.Posts).Load()

But blog.Posts become a empty collection (Zero Count).

So I want a Reload.


Solution

  • 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 usings):

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