尝试使用Entity Framework进行SaveChanges时出现异常

时间:2016-03-29 13:18:45

标签: c# wpf entity-framework checkbox mvvm

我正在使用Entity Framework 6在Visual Studio 2015中构建MVVM WPF应用程序。该应用程序有一个带有几个复选框的视图:

data %>% group_by_(~z) %>% mutate_(n = ~n())

这些复选框中的每一个都绑定到一个属性,例如:

<TextBlock Grid.Row="0"
           Grid.Column="0"
           Style="{StaticResource FieldLabel}"
           Text="Inactive" />
<CheckBox Grid.Row="0"
          Grid.Column="1"
          IsChecked="{Binding IsSelectedEmployeeInActive,
                              Mode=TwoWay}" />
<TextBlock Grid.Row="1"
           Grid.Column="0"
           Style="{StaticResource FieldLabel}"
           Text="Leave of Absence" />
<CheckBox Grid.Row="1"
          Grid.Column="1"
          IsChecked="{Binding IsSelectedEmployeeLoa,
                              Mode=TwoWay}" />
<TextBlock Grid.Row="2"
           Grid.Column="0"
           Style="{StaticResource FieldLabel}"
           Text="Archived" />
<CheckBox Grid.Row="2"
          Grid.Column="1"
          IsChecked="{Binding IsSelectedEmployeeArchived,
                              Mode=TwoWay}" />

当用户单击DataGrid上的行时,public bool IsSelectedEmployeeInActive { get { return _isSelectedEmployeeInActive; } set { if (_isSelectedEmployeeInActive == value) return; _isSelectedEmployeeInActive = value; if (value) { var count = SelectedEmployee.EmployeeStatus.Count(x => x.validEmployeeStatusID.Equals(2)); if (count.Equals(0)) { SelectedEmployee.EmployeeStatus.Add(new EmployeeStatu { employeeID = SelectedEmployee.employeeID, validEmployeeStatusID = 2, exitDate = DateTime.Now, createdDate = DateTime.Now }); } } else { var itemToRemove = SelectedEmployee.EmployeeStatus.Single(x => x.validEmployeeStatusID.Equals(2)); Context.Entry(itemToRemove).State = EntityState.Deleted; SelectedEmployee.EmployeeStatus.Remove(itemToRemove); } RaisePropertyChanged(() => IsSelectedEmployeeInActive); } } 属性将被设置。在视图模型的构造函数中,应用程序有一个事件处理程序,用于更改SelectedEmployee

SelectedEmployee

当用户单击“保存”按钮时,它会通过RelayCommand调用以下内容:

this.PropertyChanged += (o, e) =>
{
    if (e.PropertyName == nameof(this.SelectedEmployee))
    {
        IsSelectedEmployeeLoa = (SelectedEmployee.EmployeeStatus
                .Count(x => x.validEmployeeStatusID.Equals(2)) > 0);
        IsSelectedEmployeeArchived = (SelectedEmployee.EmployeeStatus
                .Count(x => x.validEmployeeStatusID.Equals(5)) > 0);
        IsSelectedEmployeeInActive = (SelectedEmployee.EmployeeStatus
                .Count(x => x.validEmployeeStatusID.Equals(4)) > 0);
    }
};

如果我在选中和取消选中后将CheckBox控件更改几次并单击“保存”,则应用程序会在上面的public void SaveEmployees() { Context.SaveChanges(); } 行上显示此异常:

  

{“存储更新,插入或删除语句影响了意外的行数(0)。实体可能在加载实体后被修改或删除。有关理解和处理乐观并发异常的信息,请参阅http://go.microsoft.com/fwlink/?LinkId=472540 。“}

如果我在Context.SaveChanges()的事件处理程序中注释掉设置复选框属性的代码,则错误消失;但后来我无法将CheckBox属性设置为数据库中的初始值。

我该如何解决这个问题?感谢。

1 个答案:

答案 0 :(得分:3)

我敢打赌,这是因为您在选中复选框时添加了新的EmployeeStatus:

            SelectedEmployee.EmployeeStatus.Add(new EmployeeStatu
            {
                employeeID = SelectedEmployee.employeeID,
                validEmployeeStatusID = 2,
                exitDate = DateTime.Now,
                createdDate = DateTime.Now
            });

然后取消选中该复选框,将其状态设置为已删除:

        var itemToRemove = SelectedEmployee.EmployeeStatus.Single(x => x.validEmployeeStatusID.Equals(2));
        Context.Entry(itemToRemove).State = EntityState.Deleted;
        SelectedEmployee.EmployeeStatus.Remove(itemToRemove);

当您调用save时,数据库无法删除它,因为它实际上从未实际添加到数据库中......它只是添加到上下文中。您需要检查它是否是新添加的记录。尝试这样的事情,我通常喜欢在发布之前测试代码,但我现在没有时间......

if (Context.Entry(itemToRemove).State != EntityState.Added)
   Context.Entry(itemToRemove).State = EntityState.Deleted;
else
   Context.Entry(itemToRemove).State = EntityState.Detached;