Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
SaveChangesAsync returns exception instead of 0

About SaveChangesAsync method, Microsoft says it's a task that represents the asynchronous save operation. The task result contains the number of state entries written to the underlying database.

According to that, some programmers use if condition to check the number of rows affected after SaveChangesAsync is run.

Here is an example: How can I confirm if an async EF6 await db.SaveChangesAsync() worked as expected?

But, what happens if an error occurs when calling SaveChangesAsync? Well, contrary to what I expected, which would be "0 lines affected", an exception is thrown, in most cases, a DbUpdateException

"Exception thrown by DbContext when the saving of changes to the database fails."

So, why are there several recommendations for using if (await context.SaveChangesAsync() > 0) once the result from database will never be zero, but instead, an exception?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

So, why are there several recommendations for using if (await context.SaveChangesAsync() > 0) once the result from database will never be zero, but instead, an exception?

First off, there are no such official recommendations. The people who provided them have no idea of the semantics of the SaveChanges operation. Which by current official EF Core documentation is:

Returns
Int32
The number of state entries written to the database.

Exceptions
DbUpdateException
An error is encountered while saving to the database.

DbUpdateConcurrencyException
A concurrency violation is encountered while saving to the database. A concurrency violation occurs when an unexpected number of rows are affected during save. This is usually because the data in the database has been modified since it was loaded into memory.

This is for SaveChanges, but the same is for Async version after awaiting it.

So, as it can be seen from the docs, the operation can return 0 and still be successful. It's because the smart update (load/modify/save) might not generate database operation. But still it is saved - because you don't ask "please force write this to database", but "please make sure this data is saved to the database". It's true that if you perform perform forced update, then 0 is never returned. But that's not essential at all.

The more important is, the success of the operation is determined as usual by the lack of exception. I don't know what is the intended usage of the return value - it might be just because it is something "we can return". Or carry over from EF6 which in turn is carry over from ADO.NET etc. Or just use it for some logging if real database CUD occurred. Who knows. But, for sure one should not use it for checking the success as in these (anti) "recommendations".

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda