Check if record in a table exist in a database through ExecuteNonQuery

前端 未结 5 465
心在旅途
心在旅途 2020-12-03 14:06

in my program i need to check if a record in the database already exists in the table using the if statement. using c# i am trying to do this through an sql con

5条回答
  •  一个人的身影
    2020-12-03 14:29

    If someday you want to use EF just do:

    private MyDb db = new MyDb();
    
    public bool UserExists(string userName, string password){
    
       return db.Users.Any(x => x.user_name.Equals(userName, StringComparison.InvariantCultureIgnoreCase)
                             && x.password.Equals(password, StringComparison.InvariantCultureIgnoreCase));
    }
    

    Or do a generic method, so you can handle multiple entites:

    public bool EntityExists(Expression> predicate) where T : class, new()
    {
       return db.Set().Any(predicate);
    }
    

    Usage:

    EntityExists(x => x.user_name.Equals(userName, StringComparison.InvariantCultureIgnoreCase)
                          && x.password.Equals(password, StringComparison.InvariantCultureIgnoreCase));
    

提交回复
热议问题