实体框架,删除和添加对象两次时InvalidOperationException
本文关键字:两次 InvalidOperationException 对象 框架 删除 添加 实体 | 更新日期: 2023-09-27 18:16:33
我使用实体框架6,数据库第一。
我有一个名为SubstanceNumbers的数据库表和一个数据网格,以及一个文本框和一些用于添加新条目的其他gui元素,SubstanceNumber有一个外键字段到Substance。
让我崩溃的场景是当我添加一个substanessubstance,删除它,添加它并再次删除它时,这不是最常见的用例,但我觉得它揭示了我所做的一些更大的错误。
My error message: System.InvalidOperationException was unhandled
Message=Saving or accepting changes failed because more than one entity of type 'SHMD_Edit.Models.EF.SubstanceNumber' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
当我添加SubstanceNumbers时,我不想设置主键字段SubstanceNumberId,因为数据库应该处理自动递增,所以它将是0,直到我实际context.SaveChanges()。
我的添加/删除命令是这样的:
public RelayCommand AddSubstanceNumberCommand
{
get
{
return new RelayCommand(
(x) =>
{
var number = new SubstanceNumber();
number.SubstanceID = Id;
number.ModifiedBy = Main.op.LoginName;
number.ModifiedDate = DateTime.Now;
number.CreatedDate = DateTime.Now;
number.Type = Converters.NumberTypeToStringConverter.translation.First(t => t.Value == SelectedNewSubstanceNumberType).Key;
number.NumberText = Validator.Normalize(NewSubstanceNumber, SelectedNewSubstanceNumberType);
var temp = NewSubstanceNumber.Replace("-", "");
number.NumberValue = Int32.Parse(temp.Substring(0, temp.Length - 1));
if (NewSubstanceNumber != null && !SubstanceNumbers.Any(sn => sn.NumberText.Replace(" ", "") == number.NumberText && sn.Type == number.Type))
SubstanceNumbers.Add(number);
NewSubstanceNumber = "";
}, param => this.CanAddSubstanceNumber);
}
}
和
public RelayCommand RemoveSubstanceNumberCommand
{
get
{
return new RelayCommand(
(x) =>
{
if (SelectedSubstanceNumber != null)
{
context.Entry(SelectedSubstanceNumber).State = EntityState.Deleted;
SubstanceNumbers.Remove(SelectedSubstanceNumber);
}
});
}
}
My table:
Column name, Data Type, Allow Nulls (is identity, identity increment=1)
SubstanceNumberID int Unchecked
SubstanceID int Unchecked
Type int Unchecked
NumberText char(16) Unchecked
NumberValue int Unchecked
CreatedDate datetime Unchecked
ModifiedDate datetime Unchecked
ModifiedBy nvarchar(16) Unchecked
RowVersion timestamp Unchecked
所以我假设上下文和我的substanenumbers列表之间有一些同步错误,但我看不出它是什么。你能指出来吗?
当你要删除的时候,像这样做
public virtual void Delete(T entity)
{
if (entity == null) throw new ArgumentNullException(typeof(T) + " cannot be null.");
try
{
DbEntityEntry dbEntityEntry = _DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
_DbSet.Attach(entity);
_DbSet.Remove(entity);
}
}
catch (Exception ex)
{
throw;
}
}
这是一个泛型类的泛型方法,但你可以得到图片。在删除之前,请检查实体的状态。如果它的状态未被删除,则将状态更改为已删除。