2

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.

7
  • There's not enough here to determine the problem. Simplistically, that exception results when you try to reference a property or method on an object instance that evaluates to null at runtime. For example, if you pull an item out of the database and fail to check if it's null before trying to display one of its properties. You need to find and identity the place in your code where this is happening. Commented Oct 7, 2015 at 17:45
  • @chrispratt Thanks for the response Chris, as per the exception, it's an EntityFramework underlying issue when execute the data query line code, and from the code above, which call do you think would cause this NullReferenceException error? I'm sure the http context which is source of IsAuthenticated wouldn't be null, so the only chance is the talent object(s) which is returned from the db query, but I can't believe the EntityFramework would provide me a null object which doesn't exist in the db. Commented Oct 8, 2015 at 7:15
  • @chrispratt P.S. I never suffer such issue in other places of code which don't use async, so my understanding is that the db context (or some operations) might not be thread safe, when a thread is initializing the db context, then another call happen and read the data which hasn't been ready, so I can only get this error accidentally, but I need somebody to double confirm if this is true. Commented Oct 8, 2015 at 7:23
  • 1
    No, that's not true at all. Entity Framework is perfectly thread-safe, as long as you don't do something silly to make it otherwise, like using the same context instance across multiple requests. My understanding is that tying into the OWIN context should be thread-safe, but at the end of the day, this is not a true, full-feature DI container. Personally, I would use a real DI container and see if that's enough to resolve your issues. Commented Oct 8, 2015 at 12:33
  • @ChrisPratt Thanks Chris, I think I figured out this issue, and you are correct, 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, any clue? Commented Oct 8, 2015 at 13:59

2 Answers 2

4

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.

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

1 Comment

While this answer doesnt solve the problem, it does confirms that it is an issue. I am also suffering from the same problem, where something in the property HttpContext.Current.User.Identity is null when the expression is being evaluated
1

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;

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.