c# - 如何区分数据网格中的新行和现有行?
问题描述
我在 WPF 应用程序中有一个普通的 DataGrid,它由ObservableCollection<T>
. 我正在使用 Dapper 更新 SQL Server 数据库。
Dapper 可以毫无问题地更新现有记录,但要将新记录放入数据库中,我必须将它们插入。所以我必须打两个 Dapper 电话;一种用于更新用户对现有记录所做的任何更改,另一种用于添加任何新记录。
如何区分ObservableCollection
用户添加的记录与加载表单时从数据库加载的原始记录?
解决方案
假设 DTO 为
public class Document
{
int Id { get; set; }
string DocumentName { get; set; }
bool IsNew { get; set; } // This field is not in the database
}
我可以使用这个事件处理程序:
private void Documents_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
foreach(Document item in e.NewItems)
{
item.IsNew = true;
}
}
标记用户添加到数据网格的任何新记录。从数据库加载原始记录后,我挂钩此处理程序:
public void LoadDocuments()
{
var documents = myIdbConnection.GetAll<Document>();
Documents = new ObservableCollection<Document>(documents);
Documents.CollectionChanged += Documents_CollectionChanged;
}
接着:
public void Save()
{
myIdbConnection.Update(Documents.Where(x=>!x.IsNew));
myIdbConnection.Insert(Documents.Where(x=>x.IsNew));
}
推荐阅读
- javascript - 如何在 Javascript 中访问函数的返回语句
- typescript - 打字稿:合并类型(与相交)
- angular - 找不到模块robotjs
- linux - 用于读取 txt 文件的 Bash 脚本,执行 while 循环并写入输出
- c++ - 在 foreach 循环中隐式转换指向 std::unique_ptr 的指针
- types - 你如何阅读 coq 量词`forall P: Set -> Prop`?
- sql-server - 在 Dockerfile 中通过 Chocolatey 安装时如何以其他用户身份安装 SQL Server Express
- python - Python:如何在不删除重复项的情况下从另一个数据框中替换一个数据框中的列值
- node.js - 如果服务器在异步回调期间崩溃,我如何记录快速端点命中?
- javascript - 通过另一个类更改类字符串变量 - 不工作