7
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_USERS table has no record(null). I also tried checking for null control(s) for currUser.

What am I missing?

Error is :

Non static method requires a target

1
  • Seems a Try / Catch is needed here...
    – Hexie
    Sep 30, 2013 at 12:56

3 Answers 3

10

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

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 :

 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.

3
  • Can you explain difference between return validateUser.Any(); and return (validateUser.FirstOrDefault() != null);? Why you suggest 2nd instead of 1st? Oct 2, 2013 at 9:36
  • In fact, I think it is the same thing. The Any is more simple. The problems came from the Where clause in this problem.
    – Rom Eh
    Oct 2, 2013 at 9:49
  • Adding if (dbContext != null) check worked for me. Can you explain the reason? Apr 27, 2016 at 19:33
2

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

Try checking the context and the var result values:

 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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.