我有两个窗户。它们具有单独的DbContext
对象。
Window1用于数据视图。
Window2是用于数据编辑的对话框窗口。
在Window2中编辑数据后-我正在使用ctx.SaveChanges()
方法。
Window2数据零件视图:
<Button Name="SaveChanges" Click="SaveChanges_Click">Save</Button>
<DataGrid Name="ListBoxLayouts"> <!-- "ListBox" in a name from the past -->
</DataGrid>
后面的代码:
public Window2(ref MyContext context)
{
InitializeComponent();
ctx = context;
ctx.Layouts.Load();
ListBoxLayouts.ItemsSource = ctx.Layouts.Local;
}
private void SaveChanges_Click(object sender, RoutedEventArgs e)
{
System.Console.WriteLine(ctx.SaveChanges());
this.DialogResult = true;
this.Close();
}
当Window1从Window2获取
DialogResult
时,我正在尝试通过处理和创建新的Window1上下文来刷新数据视图ctx.Dispose();
ctx = new MyContext();
Layouts l = context.Layouts.Where(a => a.LayoutId == 1).First();
我正在获取旧版本的数据。
我的代码有什么问题?
最佳答案
您可以这样使用,然后无需手动处理它是自动的。
using (var ctx = new MyContext())
{
//your code
}
您可以使用以下文章阅读有关上下文处理的更多信息。
Working with DbContext
Managing DbContext the right way
关于c# - 如何在EF6中刷新上下文?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40005074/