假设我有这个代码,使用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);
}
}
现在让我说我实现了Foo
和Baz
。它们的bar
实例都已由不同的上下文加载,但在数据库中表示相同的记录。如果我在Mutation()
上致电Foo
,bar.Category.Name
的{{1}}将不会更新。
我如何重新加载Baz
?我几乎尝试了在网上找到的所有内容但没有成功。
例如,这不起作用
Baz.bar
整个应用程序的单个上下文将修复此跟踪问题,但这被认为是不好的做法。我希望我足够清楚!