[英]The instance of entity type 'xTestType' cannot be tracked because another instance of this type with the same key is already being tracked?
I'm trying to delete multiple rows from a table.我正在尝试从表中删除多行。 But it gives the following error after the first iteration.但它在第一次迭代后给出以下错误。 I can see primary key Id
as 0
on all the xTestType
object.我可以在所有xTestType
对象上看到主键Id
为0
。 that might be the issue.这可能是问题所在。 Why is it always giving Id
0
.为什么它总是给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);
}
}
Exception:例外:
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 (ie 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.
When you fetch data from database, and iterate over it, like:当您从数据库中获取数据并对其进行迭代时,例如:
var dataObject = await dbContext.Table.where(x=>x.UserId == model.UserId).TolistAsync();
foreach(var item in dataObject)
{
}
do not create another object, pass the fetched object directly to Delete or use it to update, because DbContext
is tracking the objects it has fetched, not the ones you create.不要创建另一个对象,将获取的对象直接传递给 Delete 或使用它来更新,因为DbContext
正在跟踪它已获取的对象,而不是您创建的对象。 for example:例如:
//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);
}
you must pass the originally fetched instance to Remove() method, see:您必须将最初获取的实例传递给 Remove() 方法,请参阅:
var dataObject = await dbContext.Table.where(x=>x.UserId == model.UserId).TolistAsync();
foreach(var item in dataObject)
{
dbContext.Table.Remove(item);
}
The issue exists because the entity framework is tracking xTestType
when you fetched all of them.问题存在是因为实体框架在您获取所有这些时正在跟踪xTestType
。 There are two approaches to handle the situation.有两种方法可以处理这种情况。
Approach 1:方法一:
DbContext.Entry(xTestTypeOld).State = EntityState.Deleted; // where xTestTypeOldis record from which you are taking xId
Approach 2 :方法二:
DbContext.Entry(xTestTypeOld).State = EntityState.Detached;
DbContext.Entry(xTestType).State = EntityState.Deleted;
I would say the first approach is the best one.我会说第一种方法是最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.