C# 如何区分datagrid中的新行和现有行?
我在一个WPF应用程序中有一个普通的DataGrid,它由一个C# 如何区分datagrid中的新行和现有行?,c#,wpf,datagrid,observablecollection,dapper,C#,Wpf,Datagrid,Observablecollection,Dapper,我在一个WPF应用程序中有一个普通的DataGrid,它由一个ObservableCollection支持。我正在使用Dapper更新SQL Server数据库 Dapper可以毫无问题地更新现有记录,但要将新记录插入数据库,我必须插入它们。所以我不得不打两个整洁的电话;一个用于更新用户对现有记录所做的任何更改,另一个用于添加任何新记录 如何区分用户添加的ObservableCollection中的记录与加载表单时从数据库加载的原始记录?假设DTO为 public class Document
ObservableCollection
支持。我正在使用Dapper更新SQL Server数据库
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;
}
}
标记用户添加到datagrid的任何新记录。从数据库加载原始记录后,我钩住此处理程序:
public void LoadDocuments()
{
var documents = myIdbConnection.GetAll<Document>();
Documents = new ObservableCollection<Document>(documents);
Documents.CollectionChanged += Documents_CollectionChanged;
}
你可以不去听。只需对新记录进行默认初始化,并使用与现有记录相同的另一个值
public class Document
{
static bool IsNewInitializer { get; set; } = false;
int Id { get; set; }
string DocumentName { get; set; }
bool IsNew { get; set; } = IsNewInitializer; // This field is not in the database
}
public void LoadDocuments()
{
Document.IsNewInitializer = false;
var documents = myIdbConnection.GetAll<Document>();
Documents = new ObservableCollection<Document>(documents);
Document.IsNewInitializer = true;
}
public void Save()
{
myIdbConnection.Update(Documents.Where(x => !x.IsNew));
myIdbConnection.Insert(Documents.Where(x => x.IsNew));
foreach (var d in Documents.Where(x => x.IsNew))
{
d.IsNew = false;
}
}
公共类文档
{
静态bool IsNewInitializer{get;set;}=false;
int Id{get;set;}
字符串DocumentName{get;set;}
bool IsNew{get;set;}=IsNewInitializer;//此字段不在数据库中
}
公共文件()
{
Document.IsNewInitializer=false;
var documents=myIdbConnection.GetAll();
文件=新的可观察收集(文件);
Document.IsNewInitializer=true;
}
公共作废保存()
{
更新(Documents.Where(x=>!x.IsNew));
插入(Documents.Where(x=>x.IsNew));
foreach(Documents.Where中的var d(x=>x.IsNew))
{
d、 IsNew=false;
}
}
public class Document
{
static bool IsNewInitializer { get; set; } = false;
int Id { get; set; }
string DocumentName { get; set; }
bool IsNew { get; set; } = IsNewInitializer; // This field is not in the database
}
public void LoadDocuments()
{
Document.IsNewInitializer = false;
var documents = myIdbConnection.GetAll<Document>();
Documents = new ObservableCollection<Document>(documents);
Document.IsNewInitializer = true;
}
public void Save()
{
myIdbConnection.Update(Documents.Where(x => !x.IsNew));
myIdbConnection.Insert(Documents.Where(x => x.IsNew));
foreach (var d in Documents.Where(x => x.IsNew))
{
d.IsNew = false;
}
}