ASP.NET 5 EF 7無法更新數據庫表中的條目

asp.net asp.net-mvc c# entity-framework entity-framework-core

我正在創建一個API,它將在數據庫中啟用CRUD功能來創建,讀取,更新和刪除記錄。

我遇到了一個問題,即由於實例共享導致我無法更新表中的條目,因此我遇到了錯誤。

cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values."

這是我的代碼:

[HttpPut("{id}")]
        public JsonResult Put(int Id, [FromBody]PackageVersion updatePackage)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (updatePackage == null || updatePackage.Id != Id)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return Json(new { status = "Bad Request" });
                    }

                    var package = _respository.GetPackageById(Id);
                    if (package == null)
                    {
                        Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return Json(new { status = "Not Found", Message = package });
                    }

                    _respository.UpdatePackage(updatePackage);
                    if (_respository.SaveAll())
                    {
                        Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return Json(updatePackage);
                    }
                }
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", ModelState = ModelState });
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", Message = ex.Message });
            }
        }

在上面的代碼中,您將注意到我首先使用repository _repository.GetPackageById(Id)獲取記錄,這允許我驗證記錄是否在數據庫中,並且我可以使用_repository.UpdatePackage(updatePackage)存儲庫繼續更新。如果我在控制器中註釋掉下面的代碼,我就可以將數據保存在數據庫中。

[HttpPut("{id}")]
        public JsonResult Put(int Id, [FromBody]PackageVersion updatePackage)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (updatePackage == null || updatePackage.Id != Id)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return Json(new { status = "Bad Request" });
                    }

                    var package = _respository.GetPackageById(Id);
                    if (package == null)
                    {
                        Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return Json(new { status = "Not Found", Message = package });
                    }

                    _respository.UpdatePackage(updatePackage);
                    if (_respository.SaveAll())
                    {
                        Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return Json(updatePackage);
                    }
                }
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", ModelState = ModelState });
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", Message = ex.Message });
            }
        }

我還確保我在啟動配置中使用AddScoped,如此線程中所述

[HttpPut("{id}")]
        public JsonResult Put(int Id, [FromBody]PackageVersion updatePackage)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (updatePackage == null || updatePackage.Id != Id)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return Json(new { status = "Bad Request" });
                    }

                    var package = _respository.GetPackageById(Id);
                    if (package == null)
                    {
                        Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return Json(new { status = "Not Found", Message = package });
                    }

                    _respository.UpdatePackage(updatePackage);
                    if (_respository.SaveAll())
                    {
                        Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return Json(updatePackage);
                    }
                }
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", ModelState = ModelState });
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", Message = ex.Message });
            }
        }

我不確定為什麼在調用它時不能將多個DBContext實例用於相同的ID。

任何建議都非常感謝。 :)

更新1:

[HttpPut("{id}")]
        public JsonResult Put(int Id, [FromBody]PackageVersion updatePackage)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (updatePackage == null || updatePackage.Id != Id)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return Json(new { status = "Bad Request" });
                    }

                    var package = _respository.GetPackageById(Id);
                    if (package == null)
                    {
                        Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return Json(new { status = "Not Found", Message = package });
                    }

                    _respository.UpdatePackage(updatePackage);
                    if (_respository.SaveAll())
                    {
                        Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return Json(updatePackage);
                    }
                }
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", ModelState = ModelState });
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { status = "Failed", Message = ex.Message });
            }
        }

一般承認的答案

像下面一樣更改存儲庫方法。這可能有所幫助。讓我們知道會發生什麼

public object GetPackageById(int id)
{ 
 return _context.PackageVersions.AsNoTracking().SingleOrDefault(p => p.Id ==id);
}



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因