如何在EF Core 2.x中重新加载集合? [英] How to reload collection in EF Core 2.x?

查看:80
本文介绍了如何在EF Core 2.x中重新加载集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个 Load 方法.

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

但是我试图处理并发冲突,我已经在 blog.Posts 中添加了 post .如果调用 Load ,则不会清除 blog.Posts ,只需将现有的 Posts 附加到其上即可.

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.

我尝试过:

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

但是 blog.Posts 变成一个空集合(零计数).

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

所以我要一个 Reload .

推荐答案

不幸的是,尽管 EntityEntry 具有 Reload 方法,但对于 ReferenceEntry却没有这样的方法 CollectionEntry (或者通常,对于前两个基础的 NavigationEntry ).而且 Reload 方法仅刷新原始属性,因此不能用于刷新导航属性.

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.

幸运的是,创建自定义按钮并不难.它需要分离(或重新加载?)所有当前收集项,将 IsLoaded 设置为 false ,将 CurrentValue 设置为 null ,然后调用 Load .

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.

类似的事情(将其放入您选择的静态类中,并使用 s添加必要的):

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

因此您可以使用所需的

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

这篇关于如何在EF Core 2.x中重新加载集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆