I put SaveChanges()
method inside a try/catch block, but I couldn't catch SqlExeption.
try
{
db.SaveChanges();
}
catch (Exception ex)
{
}
Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.
SaveChanges() always returns 0 – Entity Framework According to EF documentation, SaveChanges() should return a number of affected rows.
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.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With