实体框架删除相关实体

时间:2014-05-29 12:57:03

标签: c# wpf entity-framework data-binding wpfdatagrid

我有两个数据网格。首先显示论坛,第二个相关用户。我设法在第一个数据网格中添加和删除论坛,因为MyForums是一个ObservableCollection,我可以将CollectionChanged事件附加到它。

从xaml可以看到,第二个数据网格是第一个数据网格的子集。当我向其添加用户时,它们将保存到数据库中。但是,我很难找到删除用户的方法。我想出的就是这里的解决方案http://msdn.microsoft.com/pl-pl/data/jj574514.aspx

foreach (var users in _context.User.Local.ToList())
{
   if (users.Forum == null)
   {
      _context.User.Remove(users);
   }
   _context.SaveChanges();
}

这是有效的,但在我看来它不是很优雅,因为每次按下保存按钮,它都会通过所有用户来实现。应该有一种更聪明的方法来做到这一点。我很感激你的帮助。

我的简化模型如下所示:

Entity Framework model

xaml中的数据处理是这样完成的:

<Window.Resources>
        <CollectionViewSource Source="{Binding MyForums}" x:Key="CVSForums" x:Name="CVSForums" />
        <CollectionViewSource Source="{Binding User, Source={StaticResource CVSForums}}" x:Key="CVSUsers" x:Name="CVSUsers" />
</Window.Resources>

<DataGrid ItemsSource="{Binding Source={StaticResource CVSForums}}" x:Name="ForumList" />
<DataGrid ItemsSource="{Binding Source={StaticResource CVSUsers}}" AutoGenerateColumns="False" >
   <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Path=UserUsername, Mode=TwoWay}" Header="UserName" x:Name="UserCol2" />
      <DataGridTextColumn Binding="{Binding Path=UserPassword, Mode=TwoWay}" Header="UserPassword" x:Name="UserCol3" />
   </DataGrid.Columns>
</DataGrid>

代码的相关部分如下所示:

MyForums = new ObservableCollection<DB.Forum>(_context.Forum.Local);
MyForums.CollectionChanged += MyForums_CollectionChanged;

void MyForums_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:

                foreach (DB.Forum single_forum in e.NewItems.OfType<DB.Forum>())
                {
                    _context.Forum.Add(single_forum);
                    var single_forumoptions = new DB.ForumOptions() { Forum = single_forum };
                    _context.ForumOptions.Add(single_forumoptions);
                    _context.SaveChanges();
                }
                break;
            case NotifyCollectionChangedAction.Remove:

                foreach (DB.Forum single_forum in e.OldItems.OfType<DB.Forum>())
                {
                    _context.Forum.Remove(single_forum);
                    _context.SaveChanges();
                }
                break;
        }
    }

0 个答案:

没有答案