简体   繁体   English

ASP.NET 5 EF 7无法更新数据库表中的条目

[英]ASP.NET 5 EF 7 cannot update entry in database table

I am creating an API that will enable CRUD functionality to Create, Read, Update, and Delete record in database. 我正在创建一个API,该API将启用CRUD功能以创建,读取,更新和删除数据库中的记录。

I am running into an issue that is not allowing me to update entry inside a table due to an instance is shared and I get below error. 我遇到了一个问题,由于实例共享,不允许我更新表中的条目,并且出现以下错误。

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."

Here is my code: 这是我的代码:

[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 });
            }
        }

In the above code you will notice I am first getting a record by using repository _repository.GetPackageById(Id) , which allows me to validate that a record is in database and I can continue to update by using _repository.UpdatePackage(updatePackage) repository. 在上面的代码中,您将注意到我首先使用存储库_repository.GetPackageById(Id)获取记录,这使我可以验证记录是否在数据库中,并且可以继续使用_repository.UpdatePackage(updatePackage)存储库进行更新。 If I comment out below code in my controller, I am able to save the data in the database. 如果我在控制器中的以下代码中注释掉,则可以将数据保存在数据库中。

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

I also made sure that I was using AddScoped in startup configuration as mentioned in this thread . 我还确保如该线程中所述在启动配置中使用AddScoped。

services.AddScoped<IAutomationRepository, AutomationRepository>();

I am not sure why I cant use multiple DBContext instances for same ID when it is called. 我不确定为什么在调用同一ID时不能使用多个DBContext实例。

Any suggestion is really appreciated. 任何建议都非常感谢。 :) :)

UPDATE 1: 更新1:

public class AutomationRepository : IAutomationRepository
    {
        private AutomationDBContext _context;

        public AutomationRepository(AutomationDBContext context)
        {
            _context = context;
        }

        public void AddPackage(PackageVersion newPackage)
        {
            _context.Add(newPackage);
        }

        public void DeletePackage(int id)
        {
            var package = _context.PackageVersions.SingleOrDefault(p => p.Id == id);
            _context.PackageVersions.Remove(package);
        }

        public IEnumerable<PackageVersion> GetAllPackages()
        {
            return _context.PackageVersions.OrderBy(p => p.PackageName).ToList();
        }

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

        public bool SaveAll()
        {
            return _context.SaveChanges() > 0;
        }

        public void UpdatePackage(PackageVersion updatePackage)
        {
            _context.Update(updatePackage);
        }

Change your repository method like below. 如下更改您的存储库方法。 This may help. 这可能会有所帮助。 Let us know what happens 让我们知道会发生什么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM