重新加载已在另一个上下文中修改的实体

时间:2018-03-15 15:18:47

标签: c# wpf entity-framework

假设我有这个代码,使用EF6和WPF

// db model
class Category
{
    public string Name { get; set; }
    ...
}

// db model
class Bar
{
    public virtual Category { get; set; }
}

class Foo
{
    private Bar bar;

    void Load()
    {
        using(var context = new ApplicationDbContext())
        {
            bar = context.Bars.First(x => x.Id == 1);
        }
    }

    void Mutation()
    {
        using(var context = new ApplicationDbContext())
        {
             context.Attach(bar);
             bar.Category.Name = "Hello";
             context.SaveChanges();
        }
    }
}

class Baz
{
    private Bar bar;

    void Load()
    {
        using(var context = new ApplicationDbContext())
        {
            bar = context.Bars.First(x => x.Id == 1);
        }
    }

    void Print()
    {
        // Reload entity???
        Console.WriteLine(bar.Category.Name);
    }
}

现在让我说我实现了FooBaz。它们的bar实例都已由不同的上下文加载,但在数据库中表示相同的记录。如果我在Mutation()上致电Foobar.Category.Name的{​​{1}}将不会更新。

我如何重新加载Baz?我几乎尝试了在网上找到的所有内容但没有成功。

例如,这不起作用

Baz.bar

整个应用程序的单个上下文将修复此跟踪问题,但这被认为是不好的做法。我希望我足够清楚!

0 个答案:

没有答案