Search code examples
c#wpfwpfdatagrid

Unable to add new record to DB using collection bound datagrid


I have a WPF DataGrid that is bound to an ObservableCollection that is populated through an Entity Framework query. I'm able to make edits to the contents of the DataGrid but for some reason I'm unable to add a new record. I can add the data in a new row but when I click Save, the new record never gets persisted to the database.

Here is how my collection is declared

public ObservableCollection<Camp> Camps { get; private set; }

populated

Camps = new ObservableCollection<Camp>( await ctx.Camps.Include( "Applications.Applicant" ).OrderByDescending( c => c.StartDate.Year ).ToListAsync() );

and bound to the datagrid

<DataGrid MinHeight="300" ItemsSource="{Binding Camps}" SelectedItem="{Binding SelectedCamp}" AutoGenerateColumns="False"
                      CanUserResizeRows="True" CanUserResizeColumns="True" CanUserSortColumns="True" CanUserReorderColumns="True" CanUserAddRows="True">

Here is the save method that should add the record to the DB

private async void SaveEntry()
{
    // Okay something is going on so that new records don't get added if they are created through the DG.
    var test = ctx.ChangeTracker.HasChanges(); // Just for testing

    if ( ctx.ChangeTracker.HasChanges() )
    {
        // Save changes
        await ctx.SaveChangesAsync();
    }
}

When I look at the "test" var, the ChangeTracker never shows true when I add a record. If I modify an existing record in the grid it works fine. Is the record not being added to the ObservableCollection when it's added to the datagrid? How can I add the record from the datagrid?


Solution

  • There is no built-in synchronization between the ObservableCollection<Camp> and the context so you should add the new Camp object to your context when it gets added to the ObservableCollection<Camp>. You could to this by handling the ObservableCollection's CollectionChanged event:

    Camps.CollectionChanged += (ss, ee) =>
    {
        switch(ee.Action)
        {
            case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                Camp newObject = ee.NewItems[0] as Camp;
                ctx.Camps.Add(newObject);
                break;
        }
    };