0

With EF, any data value in Entity instance can be saved back to database by calling SaveChanges which can be overridden to add custom action.

So I try to override SaveChanges in following way:

public override int SaveChanges(System.Data.Objects.SaveOptions options)
       {          
           try
           {
               return base.SaveChanges(options);
           }
           catch (Exception ex)
           {
               //error log here  
               //write the error message to database table errorlog             
               throw ex;
           }
       }

when SaveChange failed, I want to grab the exception and save the error message to a table in same database. With about code, even save data to table errorlog, also should call SaveChanges. How to resolve this problem?

2 Answers 2

2

Initialize a new context instance in your catch block and log the error.

   public override int SaveChanges(System.Data.Objects.SaveOptions options)
   {          
       try
       {
           return base.SaveChanges(options);
       }
       catch (Exception ex)
       {
           var context = new MyContext();

           // your log class instance populated with relevant details
           var error = new Error { Message = ex.Message; };

           context.Errors.AddObject(error);
           context.SaveChanges();

           throw;
       }
   }
Sign up to request clarification or add additional context in comments.

1 Comment

This is not working for me... Any updates on this?.
1

In addition to @Eranga's advice use separate context type just for error logging (it will map only Error entity). This new context type will not have overriden SaveChanges - that will avoid infinite loop in case of error fired during error saving.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.