簡體   English   中英

InvalidOperationException:無法跟蹤實體類型“Vessels”> 的實例,因為另一個實例

[英]InvalidOperationException: The instance of entity type 'Vessels' > cannot be tracked because another instance

我在編輯頁面上遇到了最奇怪的錯誤。

InvalidOperationException:無法跟蹤實體類型“Vessels”的實例,因為已跟蹤具有相同 {'Id'} 鍵值的另一個實例。 附加現有實體時,請確保僅附加一個具有給定鍵值的實體實例。 考慮使用 'DbContextOptionsBuilder.EnableSensitiveDataLogging' 來查看沖突的鍵值。

我用於保存功能的代碼如下我是否需要使用 AsNoTracking 我想將方法​​中的 json 舊值和新值保存到審計跟蹤記錄中,但我想它的抱怨是因為我正在訪問 _context.Vessel在容器編輯方法中?

我正在使用 asp.net core 3.1 和 ef Core 3.1.7

// POST: Vessels/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for 
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Displacement_Summer,Draught,Fuel_Consumption,Speed_MAX,Speed_Serivce,Liquid_Oil,CountryOfOrigon,CompanyId,Role,CallSign,MMSI,GrossTonnage,DateOwnedFrom,DateOwnedTo,IMONumber,Flag,Name,Company,Country,CallSign,MMSI,FishingNumber,IMONumber,LOALength,YearBuilt,VesselType,Active,isDeleted,isActive,CreatedDate,CreatedBy,MISObjectId,RelationShipId,DateBuilt,DateOSS,OfficalNumber")] Vessels vessels) {
    if (id != vessels.Id) {
        return NotFound();
    }

    Int32.TryParse(TempData.Peek("CaseId").ToString(), out Int32 resultCaseId);
    var oldValues = _context.Vessels
        .FirstOrDefault(w => w.Id == id  && w.isActive == true && w.isDeleted == false);
    string oldValuesjson = JsonConvert.SerializeObject(oldValues, Formatting.Indented);


    if (ModelState.IsValid) {

        var realtionShipId = Int32.TryParse(HttpContext.Session.GetString("relationShipId"), out int resultRelationshipId);

        var todayDate = DateTime.Now;
        try {

            vessels.isActive = true;
            vessels.isDeleted = false;
            vessels.Flag = vessels.Flag.ToLower();
            // we only want to change this information if the date is differnt no need if its the same person.
            if (vessels.LastModfiedDate != todayDate) {
                vessels.LastModfiedDate = DateTime.Now;
                vessels.LastModfiedBy = HttpContext.Session.GetString("Intitals");

            }
            if (HttpContext.Session.GetString("Intitals") != vessels.LastModfiedBy)
                vessels.LastModfiedBy = HttpContext.Session.GetString("Intitals");
            vessels.isActive = true;
            vessels.isDeleted = false;
            vessels.MISObjectId = resultCaseId;
            _context.Update(vessels);
            await _context.SaveChangesAsync();


            string newValuesjson = JsonConvert.SerializeObject(vessels, Formatting.Indented);




            var tennantId = await GetCurrentTennantId();
            var caseOfficer = _context.Users.Where(w => w.Id == tennantId.ToString()).FirstOrDefault();


            MISAuditTrail _auditrail = new MISAuditTrail();
            _auditrail.MISObjectId = resultCaseId;
            _auditrail.TennantId = tennantId;
            _auditrail.Action = "Vessel Updated ";
            _auditrail.Update= vessels.Name;
            _auditrail.CreatedBy = caseOfficer.FirstName;
            _auditrail.CreatedDate = DateTime.Now;
            _auditrail.isActive = true;
            _auditrail.isDeleted = false;
            _auditrail.OldFieldValues = oldValuesjson;
            _auditrail.NewFieldValues = newValuesjson;
            

            _context.Add(_auditrail);
            await _context.SaveChangesAsync();

            _toast.AddSuccessToastMessage($"You successfully Updated a Vessel  {vessels.Id.ToString("d8")} for ENF {resultCaseId.ToString("d8")}");

        } catch (Exception ex) {
            if (!VesselsExists(vessels.Id)) {
                return NotFound();
            } else {
                throw;
            }
        }
        SetupViewBags();
        return RedirectToAction("Edit", "MisObjects", new { Id = resultCaseId });


    }
    SetupViewBags();
    return View(vessels);
}

在這個調用中做 AsNoTracking() 就足夠了。

var oldValues = _context.Vessels.AsNoTracking()
            .FirstOrDefault(w => w.Id == id  && w.isActive == true && w.isDeleted == false);

InvalidOperationException:無法跟蹤實體類型“Vessels”> 的實例,因為另一個實例

在這個調用中做 AsNoTracking() 就足夠了。

我覺得這就夠了,看看這個

為了更新 ef core 中的數據,您也可以使用此編碼來避免錯誤:

           var oldValues = _context.Vessels.FirstOrDefault(w => w.Id == id  && 
                           w.isActive == true && w.isDeleted == false);
            oldValues.isActive = true;
            oldValues.isDeleted = false;
            oldValues.Flag = vessels.Flag.ToLower();
            // we only want to change this information if the date is differnt no need if its the same person.
            if (vessels.LastModfiedDate != todayDate)
            {
                oldValues.LastModfiedDate = DateTime.Now;
                oldValues.LastModfiedBy = HttpContext.Session.GetString("Intitals");

            }
            if (HttpContext.Session.GetString("Intitals") != vessels.LastModfiedBy)
                oldValues.LastModfiedBy = HttpContext.Session.GetString("Intitals");
            oldValues.isActive = true;
            oldValues.isDeleted = false;
            oldValues.MISObjectId = resultCaseId;
            _context.Update(oldValues);
           await _context.SaveChangesAsync();

暫無
暫無

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

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