How to get list of modified objects in Entity Framework 5

泄露秘密 提交于 2019-11-29 02:02:31

问题


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

回答1:


List<Object> modifiedOrAddedEntities = context.ChangeTracker.Entries()
 .Where(x => x.State == System.Data.EntityState.Modified 
        || x.State == System.Data.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.



来源:https://stackoverflow.com/questions/17463415/how-to-get-list-of-modified-objects-in-entity-framework-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!