【问题标题】:What is the correct way to change the context when using a DataGridView?使用 DataGridView 时更改上下文的正确方法是什么?
【发布时间】:2014-11-12 13:03:30
【问题描述】:

我对进行这些更改感到非常困惑。

假设我们在数据库中有一个表,我们称之为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

我想我错过了一块拼图。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我认为您缺少的部分是数据访问层。 如果您在这一层内公开上下文,您可以定义一些规则来规范您的代码。

      上下文->数据访问层->表示层

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

       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)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多