I am getting the oddest of error on my edit page.
InvalidOperationException: The instance of entity type 'Vessels' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
The code I am using for the save function is the following do I need to use AsNoTracking I am wanting to save the json old values and new values in the method to the audit trail record but I guess its complaining cause i am accessing _context.Vessel in the Vessel Edit method ?
I am using asp.net core 3.1 and 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);
}
Is doing AsNoTracking() Enough on this call.
var oldValues = _context.Vessels.AsNoTracking()
.FirstOrDefault(w => w.Id == id && w.isActive == true && w.isDeleted == false);
InvalidOperationException: The instance of entity type 'Vessels' > cannot be tracked because another instance
Is doing AsNoTracking() Enough on this call.
I think this is enough, have a look for this .
For updating data in ef core, you can also use this coding to avoid the error:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.