使用DataGridView时更改上下文的正确方法是什么?

时间:2014-11-12 13:03:30

标签: c# entity-framework datagridview entity-framework-4 bindingsource

我对完成这些更改感到非常困惑。

假设我们在数据库中有一个表,我们可以将其称为Customers

我们通过使用实体框架从表中获取数据,如下所示: List<Customers> customers = context.Customers.ToList();

我们还有一个BindingSource,我们使用List<Customers作为数据源: bindingSource1.DataSource = customers;

最后,我们将绑定源指定为DataGridView的数据源: dataGridView1.DataSource = bindingSource1;

现在假设我们想要添加一个新客户。对数据执行添加/更改的正确方法是什么?我们应该添加/更新List<Customers>,最后只保存上下文吗?

同时,取消更改的正确方法是什么?假设我们使用了这里提到的一些建议: How to Refresh DbContext 和这里: https://code.msdn.microsoft.com/How-to-undo-the-changes-in-00aed3c4

当取消上下文中的更改(所有修改,删除和添加的条目都被取消)时,我们如何更新DataGridViewBindingSource

我想我错过了一块拼图。

2 个答案:

答案 0 :(得分:1)

我来到解决方案,它是使用双向数据绑定。这样,当我们从网格中添加,编辑或删除记录时,各方都会收到通知。微软在这里有一个教程LINK,但还有其他方法。

答案 1 :(得分:0)

我认为你缺少的那块拼图是DataAccess Layer。 如果您在此图层中公开上下文,则可以定义一些规则来规范您的代码。

上下文 - &gt; 数据访问层 - &gt;表示层

通过这种方式,您可以根据需要处理上下文,您可以设计一个方法,以便现在返回客户的完整表格:

 List<Customers> customers = context.Customers.ToList(); 

但您也可以设计一种方法,将单个客户添加或修改到上下文并保存更改:

public void UpdateCustomer (Csutomer customer)
{
    using (var ctx = new Context())
    {
        ctx.Customer.ApplyChanges(customer);
        ctx.SaveChanges(); // 
    }            
}

在最后一种方法中,您可以为操作分配EntityState并使用:

 if (entity.EntityState == EntityState.Modified || entity.EntityState == EntityState.Deleted) 
 { 
   context.Refresh(RefreshMode.StoreWins, entity); 
 } 
 else if (entity.EntityState == EntityState.Added) 
 {  
   context.Detach(entity); 
 } 

您可以处理上下文刷新。

现在唯一剩下的就是它决定如何激活刷新你的表示层(DataGridView)