如何区分数据网格中的新行和现有行?

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

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

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


慕桂英546537
浏览 132回答 2
2回答

慕仙森

假设 DTO 为public class Document{&nbsp; &nbsp; int Id { get; set; }&nbsp; &nbsp; string DocumentName { get; set; }&nbsp; &nbsp; bool IsNew { get; set; } // This field is not in the database}我可以使用这个事件处理程序:private void Documents_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e){&nbsp; &nbsp; foreach(Document item in e.NewItems)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; item.IsNew = true;&nbsp; &nbsp; }}标记用户添加到数据网格的任何新记录。从数据库加载原始记录后,我钩住了这个处理程序:public void LoadDocuments(){&nbsp; &nbsp; var documents = myIdbConnection.GetAll<Document>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; Documents = new ObservableCollection<Document>(documents);&nbsp; &nbsp; Documents.CollectionChanged += Documents_CollectionChanged;}接着:public void Save(){&nbsp; &nbsp; myIdbConnection.Update(Documents.Where(x=>!x.IsNew));&nbsp; &nbsp; myIdbConnection.Insert(Documents.Where(x=>x.IsNew));}

桃花长相依

您可以省去事件监听。只需使用另一个值对新记录进行默认初始化即可。public class Document{&nbsp; &nbsp; static bool IsNewInitializer { get; set; } = false;&nbsp; &nbsp; int Id { get; set; }&nbsp; &nbsp; string DocumentName { get; set; }&nbsp; &nbsp; bool IsNew { get; set; } = IsNewInitializer; // This field is not in the database}public void LoadDocuments(){&nbsp; &nbsp; Document.IsNewInitializer = false;&nbsp; &nbsp; var documents = myIdbConnection.GetAll<Document>();&nbsp; &nbsp; Documents = new ObservableCollection<Document>(documents);&nbsp; &nbsp; Document.IsNewInitializer = true;}public void Save(){&nbsp; &nbsp; myIdbConnection.Update(Documents.Where(x => !x.IsNew));&nbsp; &nbsp; myIdbConnection.Insert(Documents.Where(x => x.IsNew));&nbsp; &nbsp; foreach (var d in Documents.Where(x => x.IsNew))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; d.IsNew = false;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP