Reputation: 13931
I have two windows. They have separate DbContext
objects.
Window1 is for data view.
Window2 is a dialog window for data editing.
After I edit data in Window2 - I'm using ctx.SaveChanges()
method.
Window2 data part view:
<Button Name="SaveChanges" Click="SaveChanges_Click">Save</Button>
<DataGrid Name="ListBoxLayouts"> <!-- "ListBox" in a name from the past -->
</DataGrid>
Code behind:
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();
}
When Window1 gets DialogResult
from Window2 - I'm trying to refresh data view by disposing and creating new Window1 context
ctx.Dispose();
ctx = new MyContext();
Layouts l = context.Layouts.Where(a => a.LayoutId == 1).First();
and I'm getting old version of data.
What is wrong with my code?
Upvotes: 3
Views: 1442
Reputation: 1800
I think your problem is with your binding of the Layout
data rather than reloading the context. You might not actually be saving your changes because the data isn't bound correctly.
Judging by method names I am assuming you are using WinForms. As such, try the following.
Add using System.Data.Entity
then try
ListBoxLayouts.ItemsSource = ctx.Layouts.Local.ToBindingList();
Upvotes: 0
Reputation: 65870
You can use like this.Then no need to dispose it manually.It's automatic.
using (var ctx = new MyContext())
{
//your code
}
You can read more about context handling using below articles.
Managing DbContext the right way
Upvotes: 4