c# - datagridview 绑定(bind)到实体不更新数据库

标签 c# winforms entity-framework datagridview

我正在从一个实体对象填充一个网格,它可以很好地显示数据。当我进行更改并将其保存回来时,没有任何更新。

这是我的代码:

在我的加载事件中:

  var query = from c in _entities.PaymentTypes
              where c.CorporationId == _currentcorp.CorporationId
              select
                new DataBindingProjection
                  {
                    PaymentTypeId = c.PaymentTypeId,
                    CorporationId = c.CorporationId,
                    TokenId = c.TokenId,
                    IsActive = c.IsActive,
                    Description = c.Description,
                    CashChargeCodeType = c.CashChargeCodeType,
                    SortOrder = c.SortOrder,
                    ExcludeCreditCode = c.ExcludeCreditCodes,
                    IsUpdated = c.IsUpdated,
                    IsAdded = c.IsAdded,
                    ClearUpdatedAndAdded = c.ClearUpdateAndAdded
                  };
  dataGridView_PaymentTypes.DataSource = query.ToList();

我的类(class):

private class DataBindingProjection
{
  public Guid PaymentTypeId { get; set; }
  public Guid CorporationId { get; set; }
  public Guid TokenId { get; set; }
  public bool IsActive { get; set; }
  public string Description { get; set; }
  public int CashChargeCodeType { get; set; }
  public int SortOrder { get; set; }
  public int ExcludeCreditCode { get; set; }
  public bool IsUpdated { get; set; }
  public bool IsAdded { get; set; }
  public bool ClearUpdatedAndAdded { get; set; }
}

在保存更改的按钮中:

private void button_SaveChanges2_Click(object sender, EventArgs e)
{
  button_SaveChanges2.Enabled = false;
  _entities.SaveChanges();
  timer1.Enabled = true;
  button_SaveChanges2.Enabled = true;
}

我做错了什么?

回应 bmused:

在类级别定义:

private SuburbanPortalEntities _entities;

在我的负载中定义:

  var bs = new BindingSource();
  _entities.PaymentTypes.Where(x => x.CorporationId == _currentcorp.CorporationId).Load;
  bs.DataSource = _entities.PaymentTypes.Local.ToBindingList();
  dataGridView_PaymentTypes.DataSource = bs;

显示无法加载符号Load和Local:

enter image description here

最佳答案

可以通过创建 IBindinglist 来实现与 Winforms 和 Entity Framework 的双向数据绑定(bind)来自 DbContext Local ObservableCollection<T>并将其设置为 DataSourceBindingSource .示例:

private BindingSource bs = new BindingSource();
private MyDbContext context = new MyDbContext();

context.MyEntities.Where(x=>x.SomeProperty == 2).Load(); 
bs.DataSource = context.MyEntities.Local.ToBindingList(); 
myDataGridView.DataSource = bs;

关于c# - datagridview 绑定(bind)到实体不更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16490601/

相关文章:

c# - Windows 7 跳转列表

c# - TextBox没有BorderStyle属性

c# - ListViewItem 的组未通过另一个集合保留

c# - 如何使用按钮向 DataGridView 添加新行

C# Entity Framework 延迟加载(如果未分离)

c# - 使用 WHERE IN 子句使用 Entity Framework 在 PostgreSQL 中删除多行

c# - 如何使用 Entity Framework 从 WCF 内部提取数据到客户端

c# - 我需要使用sql server 2005数据在asp net 3.5中动态生成问卷

c# - ASP.Net 将文档转换和合并为单个 PDF

c# - 如何检测当前按下的键?