viv*_*una 3 c# entity-framework entity-framework-core asp.net-core aspnetboilerplate
我正在尝试从表中删除多行.但它在第一次迭代后出现以下错误.我可以看到主键Id为0所有的xTestType对象.这可能是问题所在.为什么总是给予Id 0.
foreach (var temp in oldxDetails.TestTypes)
{
if (deleteTestTypes.Contains(input.Id))
{
var xTestType = new xTestType
{
xId = xId,
TestTypeMasterId = temp.Id
};
await _xTestRepository.DeleteAsync(xTestType);
}
}
Run Code Online (Sandbox Code Playgroud)
例外:
The instance of entity type 'xTestType' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.
存在此问题是因为实体框架xTestType在您提取所有实体时都在跟踪。有两种方法可以处理这种情况。
方法1:
DbContext.Entry(xTestTypeOld).State = EntityState.Deleted; // where xTestTypeOldis record from which you are taking xId
Run Code Online (Sandbox Code Playgroud)
方法2:
DbContext.Entry(xTestTypeOld).State = EntityState.Detached;
DbContext.Entry(xTestType).State = EntityState.Deleted;
Run Code Online (Sandbox Code Playgroud)
我想说第一种方法是最好的方法。
小智 5
从数据库中获取数据并迭代它时,如:
var dataObject = await dbContext.Table.where(x=>x.UserId == model.UserId).TolistAsync();
foreach(var item in dataObject)
{
}
Run Code Online (Sandbox Code Playgroud)
不要创建另一个对象,将获取的对象直接传递给Delete或使用它来更新,因为DbContext它跟踪它所获取的对象,而不是你创建的对象.例如:
//Wrong code
var dataObject = await dbContext.Table.where(x=>x.UserId == model.UserId).TolistAsync();
foreach(var item in dataObject)
{
var x=new DataObject()
{
x=item.Id
};
dbContext.Table.Remove(x);
}
Run Code Online (Sandbox Code Playgroud)
您必须将最初提取的实例传递给Remove()方法,请参阅:
var dataObject = await dbContext.Table.where(x=>x.UserId == model.UserId).TolistAsync();
foreach(var item in dataObject)
{
dbContext.Table.Remove(item);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4339 次 |
| 最近记录: |