Entity Framework Core, discard and update a datagridview

c# entity-framework-core winforms

Question

I have a Winforms test application that I'm using to try to learn about Entity Framework Core.

I have a datagridview bound to my table and I can edit fields and call context.SaveChanges() - works fine.

What if I have edited several cells on different rows, deleted and added a row, then changed my mind and I don't want to save? How can I discard the changes and refresh the datagridview with the original data?

I call EntityFrameworkQueryableExtensions.Load(context.entity) and then dataGridView1.Refresh() but my form remains unchanged with my changes.

dataGridView1.DataSource = context.enity.Local.ToBindingList();
1
0
10/10/2018 4:07:35 PM

Popular Answer

To load data from database you have to instantiate the Context again:

context = new SampleDbContext(options);

then you can reload your grid any way that's possible. I think the easiest possible way is to assign it again:

dataGridView.DataSource = context.MyDbSet;

And one more thing (just in case you want to learn more); EF is not designed to be used with long lived contexts. The best way to use EF is to dispose the DbContext instance after you are done with it:

using(var ctx = new SampleDbContext()){
    instances = ctx.MyDbSet....
}
0
10/11/2018 7:58:10 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