簡體   English   中英

無法跟蹤實體類型“xTestType”的實例,因為已跟蹤具有相同鍵的此類型的另一個實例?

[英]The instance of entity type 'xTestType' cannot be tracked because another instance of this type with the same key is already being tracked?

我正在嘗試從表中刪除多行。 但它在第一次迭代后給出以下錯誤。 我可以在所有xTestType對象上看到主鍵Id0 這可能是問題所在。 為什么它總是給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);
  }
}

例外:

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.

當您從數據庫中獲取數據並對其進行迭代時,例如:

var dataObject = await dbContext.Table.where(x=>x.UserId == model.UserId).TolistAsync();
foreach(var item in dataObject)
{ 

}

不要創建另一個對象,將獲取的對象直接傳遞給 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);
}

您必須將最初獲取的實例傳遞給 Remove() 方法,請參閱:

var dataObject = await dbContext.Table.where(x=>x.UserId == model.UserId).TolistAsync();
foreach(var item in dataObject)
{ 
    dbContext.Table.Remove(item);
}

問題存在是因為實體框架在您獲取所有這些時正在跟蹤xTestType 有兩種方法可以處理這種情況。

方法一:

DbContext.Entry(xTestTypeOld).State = EntityState.Deleted;  // where xTestTypeOldis record from which you are taking xId

方法二:

DbContext.Entry(xTestTypeOld).State = EntityState.Detached;
DbContext.Entry(xTestType).State = EntityState.Deleted;

我會說第一種方法是最好的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM