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

c# entity-framework try-catch

Question

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

try
 { 
     db.SaveChanges();
 }
 catch (Exception ex)
 {
 }
1
12
7/25/2014 2:17:32 PM

Popular Answer

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

14
7/25/2014 2:38:18 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow