I have an ordinary DataGrid in a WPF application that is backed by an ObservableCollection<T>
. I am updating a SQL Server database using Dapper.
Dapper can update existing records without problems, but to get new records into the database I have to insert them. So I have to make two Dapper calls; one to update any changes made by the user to existing records, and one to add any new records.
How do I distinguish the records in the ObservableCollection
that have been added by the user from the original ones that were loaded from the database when the form was loaded?
You can spare event listening. Just make default initialization for new records with another value as for existing.
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;
}
}