How to reload collection in EF Core 2.x?

半腔热情 提交于 2021-01-27 10:51:59

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/57060314/how-to-reload-collection-in-ef-core-2-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!