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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19094711/
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 14:04:37  来源:igfitidea点击:

Non static method requires a target

c#asp.netentity-framework

提问by Khnemu

private PMS_USERS currUser;
private bool validateUserName()
{
    dbContext = new PmsEntities();
    var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF).Where(p=> p.USERNAME == currUser.USERNAME);
    return !validateUser.Any();
}

Hello, I got an error while validating on my new user register form.

您好,我在验证我的新用户注册表时遇到错误。

My PMS_USERStable has no record(null). I also tried checking for nullcontrol(s) for currUser.

我的PMS_USERS表没有记录(null)。我也试过检查null控制(多个)currUser

What am I missing?

我错过了什么?

Error is :

错误是:

Non static method requires a target

非静态方法需要一个目标

采纳答案by Rom Eh

You should first test if currUser is null or not and your dbContext too.

您应该首先测试 currUser 是否为 null 以及您的 dbContext 。

if (currUser == null) return false;
if (dbContext == null) throw new Exception ("The dbContext has not been set");

Secondly, you can simplify your query like yhat :

其次,您可以像 yhat 一样简化您的查询:

 var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF &&  p.USERNAME == currUser.USERNAME);

And then change the return statement to :

然后将返回语句更改为:

return (validateUser.FirstOrDefault() != null);

You can alternativelly use SingleOrDefault statement insead of FirstOrDefault, if you want to be sure there is only one user corresponding to your criteria.

如果您想确保只有一个用户符合您的条件,您也可以使用 SingleOrDefault 语句代替 FirstOrDefault。

回答by Carlos Landeras

"Non static method requires a target" means that some object inside the scope is null.

“非静态方法需要目标”意味着范围内的某个对象是null.

Try checking the context and the var result values:

尝试检查上下文和 var 结果值:

 dbContext = new PmsEntities();
 if (dbContext != null && currUser != null)
 {
     var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF && p.USERNAME == currUser.USERNAME);

    if (validateUser !=null)
    {
       return !validateUser.Any();
    }
    else
       return null;
 }

Check it and tell us if you have the same exception.

检查它并告诉我们您是否有相同的异常。

回答by Sysketov Alexey

Use

private PMS_USERS currUser;
private bool validateUserName()
{
    dbContext = new PmsEntities();
    return PMS_USERS != null 
        ? var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF).Where(p=> p.USERNAME == currUser.USERNAME).Any()
        : false;
}