skip to Main Content

My code is an API that updates and creates various tables in the database. For every other class it is working except this class: Operacao. The method Update() works fine, but Create() doesn’t work.

This is the class:

public class Operacao
{
    public virtual short OperacaoID { get; set; }
    public virtual short? Codigo { get; set; }
    public virtual string Nome { get; set; }
    public virtual string? Descricao { get; set; }
    public virtual bool FlagAtivo { get; set; }
    public virtual bool FlagPadrao { get; set; }
    public virtual int DtUpdate { get; set; }
}

This is the input data from the user:

public class OperacaoDados
{
    [Key]
    [JsonIgnore]
    public short OperacaoID { get; set; }
    [NotMapped]
    public virtual string Nome { get; set; }
    public virtual string? Descricao { get; set; }
}

And this is the controller:

 [HttpPost]
 [Authorize]
 public async Task<ActionResult> PostOperacao(OperacaoDados operacaoDados)
 {
     var operacaoExistente = await _context.Operacao
                                           .FirstOrDefaultAsync(o => o.Nome == operacaoDados.Nome);

     DateTime dateTime = DateTime.UtcNow;
     long ticks = dateTime.Ticks;
     int dataInteiro = (int)(ticks & 0xFFFFFFFF);

     if (operacaoExistente != null)
     {
         operacaoExistente.Descricao = operacaoDados.Descricao;
         operacaoExistente.FlagAtivo = true;

         try
         {
             await _operacaoRepository.Update(operacaoExistente);
             return Ok("Operação atualizada com sucesso");
         }
         catch (DbUpdateConcurrencyException)
         {
             // Handle the concurrency exception here
             return Conflict("A operação que você está tentando atualizar foi modificada por outro usuário.");
         }
     }
     else
     {
         Operacao novoOperacao = new Operacao
                  {
                      Codigo = short.Parse(operacaoDados.Nome),
                      DtUpdate = dataInteiro,
                      Nome = operacaoDados.Nome,
                      Descricao = operacaoDados.Descricao,
                      FlagAtivo = true,
                      FlagPadrao = false
                  };

         var result = await _operacaoRepository.Create(novoOperacao);

         if (result != null)
         {
             return Ok("Operação cadastrada com sucesso");
         }

         return BadRequest("Erro ao salvar Operação");
    }
}

And this is the repository:

  public async Task<Operacao> Create(Operacao operacao)
  {
      _context.Operacao.Add(operacao);
      await _context.SaveChangesAsync();

      return operacao;
  }

  public async Task Update(Operacao operacao)
  {
      _context.Entry(operacao).State = EntityState.Modified;
      await _context.SaveChangesAsync();
  }

The error happens when it saves in this method: await _context.SaveChangesAsync(); in the Create() method.

This is the error:

Microsoft.EntityFrameworkCore.Database.Command: Information:
Executed DbCommand (12ms) [Parameters=[@p0=’?’ (DbType = Int16), @p1=’?’ (Size = 4000), @p2=’?’ (DbType = Int32), @p3=’?’ (DbType = Boolean), @p4=’?’ (DbType = Boolean), @p5=’?’ (Size = 4000)],
CommandType=’Text’, CommandTimeout=’30’] SET NOCOUNT ON;
INSERT INTO [Operacao] ([Codigo], [Descricao], [DtUpdate], [FlagAtivo], [FlagPadrao], [Nome])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
SELECT [OperacaoID] FROM [Operacao] WHERE @@ROWCOUNT = 1 AND [OperacaoID] = scope_identity();

Exceção gerada:
‘Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException’ em Microsoft.EntityFrameworkCore.Relational.dll
Exceção gerada:
‘Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException’ em System.Private.CoreLib.dll

2

Answers


  1. Chosen as BEST ANSWER

    I figured it out. It was an error in my SQL. The problem was resolved by removing the triggers in my table Operacao.


  2. You get a DbUpdateConcurrencyException error when the records you expected to update are not found. It is odd that you get an update error for an insert command. In my experience this can happen when a trigger deletes the row you just inserted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search