257
votes

I have a controller action that works fine on Firefox both locally and in production, and IE locally, but not IE in production. Here is my controller action:

public ActionResult MNPurchase()
{
    CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];

    decimal OP = landTitleUnitOfWork.Sales.Find()
        .Where(x => x.Min >= calculationViewModel.SalesPrice)
        .FirstOrDefault()
        .OP;

    decimal MP = landTitleUnitOfWork.Sales.Find()
        .Where(x => x.Min >= calculationViewModel.MortgageAmount)
        .FirstOrDefault()
        .MP;

    calculationViewModel.LoanAmount = (OP + 100) - MP;
    calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);

    return View(calculationViewModel);
}

Here is the stack trace I get in IE:

Error. An error occurred while processing your request. System.Reflection.TargetException: Non-static method requires a target. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) at System.Data.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me, Object instance, Object& memberValue) at System.Data.Objects.ELinq.QueryParameterExpression.TryEvaluatePath(Expression expression, ConstantExpression& constantExpression) at System.Data.Objects.ELinq.QueryParameterExpression.EvaluateParameter(Object[] arguments) at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable1 forMergeOption) at System.Data.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) at System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source) at LandTitle.Controllers.HomeController.MNRefi() at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Glimpse.Mvc3.Interceptor.InvokeActionMethodInterceptor.Intercept(IInvocation invocation) at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary``2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.b__36(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.b__20() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.b__22(IAsyncResult asyncResult)

8

8 Answers

535
votes

I think this confusing exception occurs when you use a variable in a lambda which is a null-reference at run-time. In your case, I would check if your variable calculationViewModel is a null-reference.

Something like:

public ActionResult MNPurchase()
{
    CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];

    if (calculationViewModel != null)
    {
        decimal OP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.SalesPrice)
            .FirstOrDefault()
            .OP;

        decimal MP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.MortgageAmount)
            .FirstOrDefault()
            .MP;

        calculationViewModel.LoanAmount = (OP + 100) - MP;
        calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);

        return View(calculationViewModel);
    }
    else
    {
        // Do something else...
    }
}
37
votes

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

12
votes

I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.

3
votes

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

2
votes

I face this error on testing WebAPI in Postman tool.

After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.

Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.

I hope it will use to someone...

0
votes

This could happen if you are using reflection to GetProperty of an object which is null.

0
votes

(This is a simple example about the error)

This error occurred when the Linq query get the Data from DB context while the DB Context matching ID is null. Suppose: We getting the Alumni Information from DB on the basis of Student record (reference table).

var getAlumniData = DBContext.Alumni.Where(a => a.AlumniID == loginHistory.AlumniID)
                      .Select(a => new Alumni
                       {
                          Enrollment = a.Student.Enrollment,
                          RegistrationNo = a.RegistrationNo,
                          Name = a.Name,
                       }).SingleOrDefault();

We get the matching ID from User Login History. If the user login history is null, then the loginHistory. AlumniID is null. So it error asked that the required target is needed.

0
votes

For anyone landing here encountering the error Non-static method requires a target while running MS Test [DynamicData] [DataTestMethod] unit tests, the error is likely caused by not making your static data test scenario collection static, i.e. ensure you have:

public **static** IEnumerable<object[]> MyFakeData => 
        new[]
        {
            new object[] { "Foo" },
            new object[] { "Bar" }
        };

[DynamicData(nameof(MyFakeData))]
[DataTestMethod]
public void DoMyTests(string someData) {...}

It's super annoying to debug, as there's no useful stacktrace