我正在使用 ASP.NET Core 6、EF Core 6 和 Repository/UnitOfWork 模式。我的專案遇到了一些問題,當我在存盤庫中呼叫 UpdateAsync 時,拋出了錯誤“無法跟蹤物體型別‘AppCase’的實體,因為已經跟蹤了具有相同 {} 鍵值的另一個實體”。我想我知道問題描述,我使用了 AsNoTracking()但問題還沒有解決。請問我該如何解決。
感謝您的支持,并為我的英語不好感到抱歉!
這是我的源代碼:
//MicroOrderBusiness.cs
public async Task<dynamic> CreateOrder(MicroOrderRequest requsetObject, string caseNo)
{
string processCode = "CEC1D433-C376-498B-8A80-B23DC3772024";
var caseModel = await _appCaseBusiness.PrepareAppCase(processCode, caseNo);
if (caseModel == null)
throw new Exception("Create request faield!");
var appCaseEntity = await _appCaseBusiness.AddNewCase(caseModel); // => Add new Case by using EF 6 Core via Repository and UnitOfWork**
if (appCaseEntity == null)
throw new Exception("Adding faield!");
var taskResponse = await _processTaskBusiness.ExecuteTask<MicroOrderRequest>(caseModel.FirstTaskCode, requsetObject);
if (Equals(taskResponse, null))
throw new Exception("Response task is not found!");
caseModel.CaseObjects.Add(taskResponse);
// Update case state
appCaseEntity.State = STATE.DONE;
appCaseEntity.CaseObject = JsonConvert.SerializeObject(appCase.CaseObjects);
var updateCase = await _appCaseRepository.UpdateAsync(appCaseEntity); // => Error throw here**
if (updateCase == null)
throw new Exception($"Update state case faiedl!");
return caseModel;
}
//Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseOracle(connectionString,
o => o.MigrationsAssembly(typeof(AppDbContext)
.Assembly.FullName)
.UseOracleSQLCompatibility("12")));
builder.Services.AddScoped(typeof(IUnitOfWork), typeof(AppDbContext));
uj5u.com熱心網友回復:
該錯誤已在檔案中進行了解釋:https ://learn.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#attaching-a-serialized-graph
我檢查了您的代碼,我認為該錯誤可能由以下原因引起:
跟蹤物體的序列化圖
appCaseEntity.CaseObject = JsonConvert.SerializeObject(appCase.CaseObjects);
var updateCase = await _appCaseRepository.UpdateAsync(appCaseEntity); // => Error throw here**
您可以了解更多詳細資訊并在此部分中找到解決方案
為多個作業單元重用 DbContext 實體
var appCaseEntity = await _appCaseBusiness.AddNewCase(caseModel);
........
var updateCase = await _appCaseRepository.UpdateAsync(appCaseEntity);
您將 dbcontext 注冊如下(生命周期默認為范圍):
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseOracle(connectionString,
o => o.MigrationsAssembly(typeof(AppDbContext)
.Assembly.FullName)
.UseOracleSQLCompatibility("12")));
您可以嘗試使用 Trasident 設定生命周期或使用 DbContextFactory 在不同的作業單元中創建不同的實體
builder.Services.AddDbContext<AppDbContext>((options=>........),ServiceLifetime.Transient)
查看有關使用 DbContextFactory 的檔案
如果您對此案例還有其他問題,請提供可以重現錯誤的最少代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/527206.html