Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't catch SqlException on SaveChanges() method of Entity Framework

I put SaveChanges() method inside a try/catch block, but I couldn't catch SqlExeption.

try
 { 
     db.SaveChanges();
 }
 catch (Exception ex)
 {
 }
like image 494
J - C Sharper Avatar asked Jul 25 '14 14:07

J - C Sharper


People also ask

What does the Dbcontext SaveChanges () method return?

Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.

What SaveChanges return value in Entity Framework?

SaveChanges() always returns 0 – Entity Framework According to EF documentation, SaveChanges() should return a number of affected rows.

Does SaveChanges commit?

In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.


2 Answers

SqlException is System.Data.SqlClient.SqlException class so it's normal that you can't catch this exception The EntityFramework DbContext.SaveChanges Method() can throw the following exceptions only as by MSDN

DbUpdateException
DbUpdateConcurrencyException    

DbEntityValidationException 

NotSupportedException   

ObjectDisposedException 


InvalidOperationException    

So you can do something like this for example

try
 { 
     db.SaveChanges();
 }
 catch (DbUpdateException ex)
 {
 }
catch (DbUpdateConcurrencyException ex)
 {
 }

More
The exceptions mentioned above are entity Framework Customized exceptions that only EF is responsible on When and How to trigger Them take a look at Implementing custom exceptions

like image 121
BRAHIM Kamel Avatar answered Sep 20 '22 14:09

BRAHIM Kamel


You cannot catch SqlException because it is not thrown directly, it is set as Inner Exception of the DbUpdateException.

Entity Framework is a abstraction to work with the databases, it does not depend on any Database technology directly.

Have a look at the Exceptions thrown by DbContext.SaveChanges()

like image 39
Parimal Raj Avatar answered Sep 19 '22 14:09

Parimal Raj