如何在EF6中刷新上下文
本文关键字:刷新 上下文 EF6 | 更新日期: 2023-09-27 18:12:58
我有两个窗口。它们有单独的DbContext
对象。
Window1是为数据视图。
Window2是一个用于数据编辑的对话框窗口。
在我编辑数据在Window2 -我使用ctx.SaveChanges()
方法。
windows2数据部分视图:
<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
}
你可以阅读更多关于上下文处理的文章。
使用DbContext
正确管理DbContext
我认为你的问题是你的Layout
数据的绑定,而不是重新加载上下文。您可能实际上没有保存更改,因为数据没有正确绑定。
根据方法名称判断,我假设您使用的是WinForms。因此,请尝试以下操作:
Add using System.Data.Entity
then try
ListBoxLayouts.ItemsSource = ctx.Layouts.Local.ToBindingList();
源