简体   繁体   English

无法使用集合绑定的数据网格将新记录添加到数据库

[英]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. 我有一个WPF DataGrid,它绑定到通过实体框架查询填充的ObservableCollection。 I'm able to make edits to the contents of the DataGrid but for some reason I'm unable to add a new record. 我可以对DataGrid的内容进行编辑,但是由于某些原因,我无法添加新记录。 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. 当我查看“ test”变量时,当我添加记录时,ChangeTracker从不显示true。 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? 将记录添加到数据网格时,是否未将记录添加到ObservableCollection中? How can I add the record from the datagrid? 如何从datagrid添加记录?

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> . ObservableCollection<Camp>与上下文之间没有内置的同步,因此在将新的Camp对象添加到ObservableCollection<Camp>时,应将其添加到上下文中。 You could to this by handling the ObservableCollection 's CollectionChanged event: 您可以通过处理ObservableCollectionCollectionChanged事件来实现:

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;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM