![](/img/trans.png)
[英]EF Core: the instance of entity type [EntityType] cannot be tracked because another instance with the key value{EntityId: X} is already being tracked
[英]EF Core (in-memory database) - 'The instance of entity type X cannot be tracked because another instance with the key value
我正在將 xunit 與 Entity Framework 內存數據庫一起使用。 對於每個測試,我在 memory 數據庫中創建一個新實例,然后進行處理。
運行超過 1 個測試時出現以下錯誤。
System.InvalidOperationException:“無法跟蹤實體類型“Account_Master”的實例,因為已在跟蹤另一個具有鍵值“{NUMBER_INT:1}”的實例。 附加現有實體時,請確保僅附加一個具有給定鍵值的實體實例。
據我所知,當我嘗試用假測試數據填充我的內存數據庫時,問題就出現了。 在第一個測試中,我添加了一個虛擬帳戶和一個虛擬 scope(這些由外鍵引用)。 這工作正常。
但是在下一次測試中,當我添加虛擬 scope 時,它會自動添加虛擬帳戶(即使它還不應該知道)。
我在這里有一個示例代碼項目https://github.com/welcometochristown/efCoreErrorTest
我在這個項目中有兩個數據庫上下文
FakeAccountContext
FakeSmtrSimpleContext
出於某種原因, FakeAccountContext
有效,但FakeSmtrSimpleContext
無效(即使它們幾乎相同)。
重現錯誤
Build project
Open the test explorer
Expand tests
Right click "SmtrSimpleTest" -> Run (error!)
Right click "AccountTest" -> Run (works!)
使用 Microsoft.EntityFrameworkCore.InMemory (3.1.27)
我認為關於 static 屬性在測試之間保持對實體的引用的假設是正確的。
在調試器中,在第二次測試中,在Account_Master.Add()
之前的斷點中,我們可以看到之前測試的 static SmtrSimpleDummyAccount
(一個Account_Master
)仍然存在:
我將 static 屬性更改為返回新 object 的方法,然后忘記它,而不是維護對它的 static 引用:
public static class FakeAccount
{
public static Account DummyAccount()
{
return new Account
{
NUMBER_INT = 1,
SCOPE_CHR = FakeAccountScope.Public().SCOPE_CHR
};
}
public static Account_Master SmtrSimpleDummyAccount()
{
return new Account_Master
{
NUMBER_INT = 1,
SCOPE_CHR = "Public",
};
}
}
和
public static class FakeAccountScope
{
public static AccountScope Private()
{
return new AccountScope
{
SCOPE_CHR = nameof(Private)
};
}
public static AccountScope Public()
{
return new AccountScope
{
SCOPE_CHR = nameof(Public)
};
}
public static X_Account_Scope SmtrSimplePublic()
{
return new X_Account_Scope
{
SCOPE_CHR = nameof(Public)
};
}
public static X_Account_Scope SmtrSimplePrivate()
{
return new X_Account_Scope
{
SCOPE_CHR = nameof(Private)
};
}
}
現在所有的測試都通過了:
可能也與您的FakeAccount.SmtrSimpleDummyAccount
相關: 如何創建 static lambda 以用於表達式構建?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.