微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 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();

我的课:

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;

显示它无法加载符号加载和本地:

解决方法

可以通过从DbContext Local ObservableCollection< T>创建IBindingList来实现具有Winforms和Entity Framework的双向数据绑定.并将其设置为BindingSource的DataSource.例:
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;

原文地址:https://www.jb51.cc/csharp/93848.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐