C# 非静态方法需要一个目标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13717355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:32:25  来源:igfitidea点击:

Non-static method requires a target

c#asp.net-mvcasp.net-mvc-3entity-frameworkentity-framework-5

提问by user547794

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:

我有一个控制器操作,它在本地和生产环境中都可以在 Firefox 和本地 IE 上正常工作,但不能在生产环境中正常工作。这是我的控制器操作:

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:

这是我在 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)

错误。处理您的请求时发生错误。System.Reflection.TargetException:非静态方法需要一个目标。在 System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) 在 System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfoculture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) at System.Data.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me, Object instance, Object& memberValue) 在 System.Data.Objects.ELinq.QueryParameterExpression.TryEvaluatePath(Expression expression,1 forMergeOption) at System.Data.Objects.ObjectQuery1.GetResults(Nullable 1 forMergeOption) at System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable 1 source) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source) at LandTitle.Controllers.HomeController.MNRefi() at lambda_method(Closure , ControllerBase) , Object[] ) 在 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 个参数) at Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Glimpse.Mvc3.Interceptor.InvokeActionMethodInterceptor.Intercept(IInvocation invocation) at Castle.DynamicProxy.Abstract()Invocation Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary``2 参数) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33() 在 System.Web.Mvc.Async .AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.b__36(IAsyncResult asyncResult) 在 System.Web.Mvc.Async。AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.b__20() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.b__22(IAsyncResult asyncResult)

采纳答案by Maarten

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.

我认为当您在 lambda 中使用变量时会发生这种令人困惑的异常,该变量在运行时是空引用。在您的情况下,我会检查您的变量calculationViewModel 是否为空引用。

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...
    }
}

回答by Jim Yu

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

通常它发生在目标为空时。所以最好先检查调用目标,然后再做 linq 查询。

回答by ccherwin

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.

当我们手动实例化实体而不是通过 DBContext 来解决所有导航属性时,我发现这个问题在实体框架中很普遍。如果表之间存在外键引用(导航属性)并且您在 lambda 中使用这些引用(例如 ProductDetail.Products.ID),那么如果您手动创建实体,则“产品”上下文保持为空。

回答by Shiv

I face this error on testing WebAPI in Postman tool.

我在 Postman 工具中测试 WebAPI 时遇到了这个错误。

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.

构建代码后,如果我们在调试模式下删除任何行(例如:在我的情况下,当我删除一个注释行时,会发生此错误...),则将发生“非静态方法需要目标”错误。

我再次尝试发送相同的请求。这次代码工作正常。我在 Postman 中得到了正确的响应。

I hope it will use to someone...

我希望它会用于某人...

回答by Nathan

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.

所有答案都指向带有 NRE(空引用异常)的 Lambda 表达式。我发现在使用 Linq to Entities 时也会发生这种情况。我认为指出此异常不仅限于 Lambda 表达式中的 NRE 会有所帮助。