Accidentally underlying NullReferenceException issue in EntityFramework in ASP.NET MVC 5

1.3k views Asked by At

experts

I'm running into a trouble when access the home page in my MVC 5 web site, please see the exception details below.

MVC 5.2.2

EntityFramework 6.1.1

Visual Studio 2013

System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me, Object instance, Object& memberValue)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryEvaluatePath(Expression expression, ConstantExpression& constantExpression)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.EvaluateParameter(Object[] arguments)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassc.<GetResultsAsync>b__a()
at System.Data.Entity.Core.Objects.ObjectContext.<ExecuteInTransactionAsync>d__3d`1.MoveNext()

The code is quite simple, it query data asynchronously from the data context shared in the current OwinContext, it works well as usual, but accidentally, it fail because of the error previously.

public class TalentsService : ServiceBase
{
    public async Task<List<TalentSummaryViewModel>> GetSlotlightTalents()
    {
        var talents = await DbContext.Talents.Where(t => t.IsSpotlight && IsAuthenticated).ToListAsync();

        return talents.Select(t => WrapModel(t)).ToList();
    }
}

public abstract class ServiceBase
{
    private ApplicationDbContext _dbContext;
    public ApplicationDbContext DbContext
    {
        get
        {
            return _dbContext ?? HttpContext.Current.GetOwinContext().Get<ApplicationDbContext>();
        }
        private set
        {
            _dbContext = value;
        }
    }

    public bool IsAuthenticated
    {
        get
        {
            return HttpContext.Current.Request.IsAuthenticated;
        }
    }
}

Is that multi-thread related? I can't figure out what could be the root cause, any clue would be appreciated, thanks in advance.

2

There are 2 answers

1
Alex Chen On BEST ANSWER

Thanks Chris Pratt for the response which led me to double check my code, the root cause is that:

The HttpContext.Current is null in some scenario which I'm not aware of, then the call to this property IsAuthenticated failed, so I would have to store the IsAuthenticated value in a local variable, now I could repro this issue easily when use the LoadTest tool to launch lots of request, but still not clear why does the context get lost accidentally, probably somebody else have more knowledge on this.

0
Artur Musin On

I had the same error after the 1st HTTP request to my Web API which was reproducible only if the IIS application was recycled. Apparently after restarting IIS the first incoming request was initiating data retrieval via IQueryable with inline ClientID parameter extracted from:

(HttpContext.Current.User as ClaimsPrincipal).Claims collection in asynchronous fashion.

So by the time the I/O operation was completed -- the HttpRequest context did not exist... Copying Http Claim value into separate variable and using this variable when contructing IQueryable solved the problem:

var claims = (HttpContext.Current.User as ClaimsPrincipal).Claims;