Álvaro García
Álvaro García

Reputation: 19356

entity framework 4.4: how to catch the Sql Exception?

I have a table in the database that has the users of the application. The user name is unique, so I have a unique constraint in the table.

I am doing probes and one is try to use the same user name for two users. When the error occurs, I catch the exception "Eception" and I can see that the catched exception is System.Data.Entity.Infraestructure.DbUpdateConcurrencyException and the inner exception is System.Data.OptimisticConcurrencyException.

Then I catch the DbUpdateConcurrencyException, the innter exception is the OptimisticConcurrencyException, so I try to catch this exception too.

If I try to catch the OptimisticConcurrencyException before the DbUpdateConcurrencyException, is not catch, is catch the DbUpdateConcurrencyException.

SO I don't know how I can to catch the SqlException, because I would like to catch the error of the Sql Server, to get the code.

Thanks.

Upvotes: 0

Views: 1806

Answers (3)

user551445
user551445

Reputation: 25

You can handle it use

var objContext = ((IObjectContextAdapter)ctx).ObjectContext;
     var entry = dbUpdateConcurrencyException.Entries.Single();
     if (entry.State == EntityState.Deleted)
     {
           entry.State = EntityState.Detached;
      }
      else
      {
           entry.OriginalValues.SetValues(entry.GetDatabaseValues());
            objContext.Refresh(RefreshMode.ClientWins,dbUpdateConcurrencyException.Entries.Select(e => e.Entity));
       }

Upvotes: 0

jeroenh
jeroenh

Reputation: 26772

You can't handle 'inner exceptions'. You need to inspect the actual exception thrown in your catch handler, and rethow if you can't handle it. Example:

try
{
}
catch (DbUpdateConcurrencyException ex)
{
   if (CanHandleException(ex)) 
   {
       // do what you have to do to handle the exception
   }
   else
   {
       throw; // can't handle this exception - just let it bubble up
   }
}

In the method CanHandleException you would write the logic that determines whether you can handle this exception and do something meaningful (perhaps retry the operation). You do this by inspecting the properties of the exception (message, InnerException, ...)

Upvotes: 1

sa_ddam213
sa_ddam213

Reputation: 43596

Have you tried:

   try
   {

   }
   catch (SqlException ex)
   {

   }

Upvotes: 1

Related Questions