【问题标题】:EF 5.0 WinForms Add New Row in Bound DataGridViewEF 5.0 WinForms 在绑定的 DataGridView 中添加新行
【发布时间】:2014-01-11 07:10:24
【问题描述】:
我已经使用 dbcontext 设置了绑定到实体的 dgv。工作正常。这些行显示在 dgv 中,我可以使用 SaveChanges 修改单元格和更新。但是,如果我尝试在 dgv 中添加新行,它不会被保存。如果 dgv 绑定到实体不应该自动添加新行还是我必须做一些事情来添加它?什么?请提供示例代码。接下来我将尝试从 dgv 中删除。我会有类似的问题吗?我怎样才能让它发挥作用?我在互联网上搜索了示例,但它们只限于绑定实体并且不包括添加或删除。任何帮助将不胜感激。
【问题讨论】:
标签:
winforms
entity-framework
data-binding
【解决方案2】:
.NET Framework 4 解决方案
我已经尝试删除 .ToList() 但我根本没有得到任何结果。
所以我的解决方法是:
对于删除:
关于datagridview UserDeletingRow 事件
// Get deleted entity:
myEntityType currentEntity = (myEntityType)BindingSource[e.Row.Index];
// Delete directly from context
context.myEntityType.Remove(currentEntity);
对于插入:
在保存按钮上,我遍历 BindingSource 并检查是否有任何实体的 ID == 0,然后使用 context.MyEntityType.Add(currentEntity);
添加每个实体