none
Intercepting query in DbContext

    Question

  • I am working on a project using SQL Azure. In order to handle Sql Azure Transient Errors I am using Transient Fault handling framework.

    I have a class MContext which inherits from DbContext I wrote a method override for entity framework SaveChanges() method in this class as below:

    private ITransientErrorDetectionStrategy errorDetectionStrategy = new SqlAzureTransientErrorDetectionStrategy();
    
    private RetryPolicy policy= new RetryPolicy(errorDetectionStrategy, 3);
    
     public override int SaveChanges()
            {
                return policy.ExecuteAction(() =>
                {
                    return base.SaveChanges();
                });
            }  

    This way I don't have to make code changes throughout my project where ever SaveChanges() is called.

    I want to know if there is a way to do the same for LINQ queries.

    For example:

    policy.ExecuteAction(() =>
                {
                    var x = from user in context.Users select user.Id;
                });

    Instead of making code changes throughout the project by adding the

    policy.ExecuteAction(() =>
                {
    }); 

    block for all the linq queries and enforcing others in the team to do the same, is there a way to intercept the linq query within the MContext class and apply the Transient handling?

    I can write an extension method and call it on all the queries, but again that would require code change throughout the project.

    I want to handle it in one place just like overriding the SaveChanges() method and not make changes all over the project.

    Thanks for your help!

    Mahesh

    Friday, June 14, 2013 10:47 PM

Answers