How to refresh context in EF6?

c# entity-framework-6

Question

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?

1
3
10/13/2016 10:40:40 AM

Popular Answer

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

4
10/12/2016 6:35:24 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow