3

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?

Kamil
  • 13,363
  • 24
  • 88
  • 183

2 Answers2

4

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.

Working with DbContext

Managing DbContext the right way

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • But what if I want to bind something to that context? I have datagrid that has `ItemsSource = ctx.Layouts.Local`. – Kamil Oct 12 '16 at 18:43
  • you have to use correct `context` object inside the `using` statement as shown above.Then it'll correctly `bind` and `dispose` the `context`.You don't need to handle it manually. – Sampath Oct 12 '16 at 18:46
0

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();

Source

Bradford Dillon
  • 1,750
  • 13
  • 24