简体   繁体   English

通过Ajax发布的ASP.NET Core 2.0错误更新模型

[英]Asp.net core 2.0 error updating model posted via ajax

I am sending a Post using ajax for my controller to update the records of a product, but I get the following error: 我正在使用ajax发送发给我的控制器的帖子以更新产品的记录,但是出现以下错误:

"The instance of entity type 'Produtos' cannot be tracked because another instance with the same key value for {'Cod'} 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." “无法跟踪实体类型'Produtos'的实例,因为已经跟踪了另一个具有相同{'Cod'}的键值的实例。在附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看冲突的键值。”

my knowledge is still very limited and I do not know what I am doing wrong. 我的知识仍然非常有限,我不知道自己在做什么错。

Here is where I load the data on the screen for editing: 这是我将数据加载到屏幕上进行编辑的地方:

[HttpGet]
public PartialViewResult EditaProduto(int cod)
{
    var produtos = new Produtos();
    if (cod != 0)
        produtos = _petalertaContext.Produtos.Where(c => c.Cod == cod).SingleOrDefault();

    return PartialView("_ProdutoCadAlt", produtos);
}

Here is where I create or update the product in the database: 这是我在数据库中创建或更新产品的位置:

[HttpPost]
public IActionResult GravaProduto([FromBody] Produtos produto)
{
    if (ModelState.IsValid)
    {
        try
        {
            int codShop = Convert.ToInt32(new UserLogado(this.User).PegaDados("cod"));
            produto.Codshop = codShop;

            Produtos prodAtual = _petalertaContext.Produtos.Find(produto.Cod);
            string strResp = "Produto alterado com sucesso!";

            if (prodAtual == null)
            {
                strResp = "Produto adicionado com sucesso!";

                prodAtual = _petalertaContext.Produtos.Where(c => c.Nome.ToUpper() == produto.Nome.ToUpper() && c.Codshop == codShop).SingleOrDefault();

                if (prodAtual != null)
                    return Content("Erro: Você já possui o produto " + produto.Nome + " cadastrado!");

                _petalertaContext.Add(produto);

            }
            else
            {
                _petalertaContext.Update(produto); //<== ERROR
            }

            _petalertaContext.SaveChanges();
            return Content(strResp);
        }
        catch (DbUpdateConcurrencyException ex)
        {
            return Content("Erro ao gravar produto: " + ex.Message + " : " + ex.InnerException?.Message);
        }
    }

    return Content("Erro: Não foi possível gravar o produtoes!");
}

Thanks for any help, thank you! 感谢您的帮助,谢谢!

I believe it has to do with this line: 我相信这与以下行有关:

 Produtos prodAtual = _petalertaContext.Produtos.Find(produto.Cod);

You already have produto so you don't need to get it again. 您已经produto ,这样你就不需要再得到它。

I would just do this: 我会这样做:

produto.Codshop = codShop;
DbEntityEntry<Produtos> entry = _petalertaContext.Entry(produto);
entry.State = EntityState.Modified;
_petalertaContext.SaveChanges();

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

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