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

David Silva-Barrera
  • 1,006
  • 8
  • 12
Ozan
  • 85
  • 1
  • 2
  • 8

3 Answers3

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.

Rom Eh
  • 1,981
  • 1
  • 16
  • 33
  • Can you explain difference between `return validateUser.Any();` and `return (validateUser.FirstOrDefault() != null);`? Why you suggest 2nd instead of 1st? – Hamlet Hakobyan Oct 02 '13 at 09: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 02 '13 at 09:49
  • Adding if (dbContext != null) check worked for me. Can you explain the reason? – Amey Khadatkar Apr 27 '16 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.

Daniel Saidi
  • 6,079
  • 4
  • 27
  • 29
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
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;
}