﻿namespace EntityFramework.Filters
{
    using System.Data.Entity.Core.Common.CommandTrees;
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Infrastructure.Interception;
    using System.Linq;

    public class FilterInterceptor : IDbCommandTreeInterceptor
    {
        public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
        {
            if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
            {
                var queryCommand = interceptionContext.Result as DbQueryCommandTree;
                if (queryCommand != null)
                {
                    var newQuery =
                        queryCommand.Query.Accept(new FilterQueryVisitor(interceptionContext.DbContexts.First()));
                    interceptionContext.Result = new DbQueryCommandTree(
                        queryCommand.MetadataWorkspace, queryCommand.DataSpace, newQuery);
                }
            }
        }
    }
}
namespace EntityFramework.Filters
{
    using System.Data.Entity.Core.Common.CommandTrees;
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Infrastructure.Interception;
    using System.Linq;

    public class FilterInterceptor : IDbCommandTreeInterceptor
    {
        public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
        {
            if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
            {
                var queryCommand = interceptionContext.Result as DbQueryCommandTree;
                if (queryCommand != null)
                {
                    var context = interceptionContext.DbContexts.FirstOrDefault();
                    if (context != null)
                    {
                        var newQuery =
                            queryCommand.Query.Accept(new FilterQueryVisitor(context));
                        interceptionContext.Result = new DbQueryCommandTree(
                            queryCommand.MetadataWorkspace, queryCommand.DataSpace, newQuery);
                    }
                }
            }
        }
    }
}

Add DbContext null check to FieldInterceptor.cs
Add DbContext null check to FieldInterceptor.cs

In some cases (outlined under "caveat" here, http://entityframework.codeplex.com/wikipage?title=Interception) EntityFramework interceptors may not have any DbContexts associated with them.  The current code will cause a null reference exception.  This can be replicated by using a profiling tool such as Glimpse.EF6 to a project using EntityFramework.Filters.  This PR adds a null check for context before continuing with filter execution.