Doan Cuong
Doan Cuong

Reputation: 2614

How to get list of modified objects in Entity Framework 5

I'm binding list of entities to a data grid view like this:

var orders = context.Order.ToList();

BindingList<Order> orderList = new BindingList<Order>(orders);

dataGridView1.DataSource = orderList;

User can edit or add new directly on datagridview. When user click Save button, in order to optimize performance, I want to retrieve list of entities that has been changed/new to perform insert/update. How can I achieve this?

EDIT Define add new row to gridview:

BindinList<Order> orders = (BindingList<Order>)dataGridView1.Datasource;

order.Add(new Order());

EDIT 2 Solve:

BindinList<Order> orders = (BindingList<Order>)dataGridView1.Datasource;

Order order = new Order();

context.Order.Add(order);

order.Add(order);

Upvotes: 24

Views: 21642

Answers (1)

user1914530
user1914530

Reputation:

List<Object> modifiedOrAddedEntities = context.ChangeTracker.Entries()
 .Where(x => x.State == System.Data.Entity.EntityState.Modified 
        || x.State == System.Data.Entity.EntityState.Added)
 .Select(x=>x.Entity).ToList();

When binding EF entities to a DataGridView it is often preferable to create an IBindingList from the DbSet.Local ObservableCollection. This way you get two way databinding and your new entities are automatically added to the context when adding via BindingSource.Add() or IBindingList.Add(). The simplest way to get this working, once properly bound, is to set DataGridView.AllowUserToAddRows to true and new rows the users enter will be new entities Added to the context.

context.Orders.Load();
BindingList<Order> bindingList = context.Orders.Local.ToBindingList();
BindingSource ordersBindingSource = new BindingSource();
ordersBindingSource.DataSource = bindingList;
dataGridView1.DataSource = ordersBindingSource ;

System.Data.Entity must be referenced to use .ToBindingList() and you must be using EF4.1 or greater.

Upvotes: 49

Related Questions