首页 > 解决方案 > 如何区分数据网格中的新行和现有行?

问题描述

我在 WPF 应用程序中有一个普通的 DataGrid,它由ObservableCollection<T>. 我正在使用 Dapper 更新 SQL Server 数据库。

Dapper 可以毫无问题地更新现有记录,但要将新记录放入数据库中,我必须将它们插入。所以我必须打两个 Dapper 电话;一种用于更新用户对现有记录所做的任何更改,另一种用于添加任何新记录。

如何区分ObservableCollection用户添加的记录与加载表单时从数据库加载的原始记录?

标签: c#wpfdatagridobservablecollectiondapper

解决方案


假设 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));
}

推荐阅读