简体   繁体   English

InvalidOperationException:无法跟踪实体类型“Vessels”> 的实例,因为另一个实例

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

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. InvalidOperationException:无法跟踪实体类型“Vessels”的实例,因为已跟踪具有相同 {'Id'} 键值的另一个实例。 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.考虑使用 'DbContextOptionsBuilder.EnableSensitiveDataLogging' 来查看冲突的键值。

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 ?我用于保存功能的代码如下我是否需要使用 AsNoTracking 我想将方法​​中的 json 旧值和新值保存到审计跟踪记录中,但我想它的抱怨是因为我正在访问 _context.Vessel在容器编辑方法中?

I am using asp.net core 3.1 and ef Core 3.1.7我正在使用 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);
}

Is doing AsNoTracking() Enough on this call.在这个调用中做 AsNoTracking() 就足够了。

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 InvalidOperationException:无法跟踪实体类型“Vessels”> 的实例,因为另一个实例

Is doing AsNoTracking() Enough on this call.在这个调用中做 AsNoTracking() 就足够了。

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:为了更新 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.

相关问题 InvalidOperationException:无法跟踪实体类型&#39;ApplicationUser&#39;的实例 - InvalidOperationException: The instance of entity type 'ApplicationUser' cannot be tracked 实体框架核心 - 无法跟踪实体类型的实例,因为已在跟踪具有键值的另一个实例 - Entity framework Core - The instance of entity type cannot be tracked because another instance with the key value is already being tracked 无法跟踪实体类型“Entity”的实例,因为已跟踪另一个具有与 {'Id'} 相同键值的实例 - The instance of entity type 'Entity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked 无法跟踪实体类型的实例,因为已在跟踪具有相同键的该类型的另一个实例 - The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked EF:无法跟踪实体类型X的实例,因为已经跟踪了具有相同密钥的此类型的另一个实例 - EF: The instance of entity type X cannot be tracked because another instance of this type with the same key is already being tracked 实体类型的实例……无法跟踪,因为已经在跟踪具有相同键的此类型的另一个实例 - The instance of entity type … cannot be tracked because another instance of this type with the same key is already being tracked 无法跟踪实体类型“xTestType”的实例,因为已跟踪具有相同键的此类型的另一个实例? - The instance of entity type 'xTestType' cannot be tracked because another instance of this type with the same key is already being tracked? 无法跟踪实体类型“ SalesOrder”的实例,因为已经跟踪了具有相同键的该类型的另一个实例 - The instance of entity type 'SalesOrder' cannot be tracked because another instance of this type with the same key is already being tracked 无法跟踪实体类型“ TestType”的实例,因为已经跟踪了具有相同键的该类型的另一个实例 - The instance of entity type 'TestType' cannot be tracked because another instance of this type with the same key is already being tracked 无法跟踪实体类型“产品”的实例,因为已在跟踪具有相同键值的另一个实例 - The instance of entity type 'Product' cannot be tracked because another instance with the same key value is already being tracked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM