Validate the username and password using LINQ

1

Goodnight I would like you to help me I am making a query with Linq of the programming language c # since I am doing a validation for a user login my code is this:

 public class D_Usuario
    {
        private DataModel.DataModelDataContext contexto = new DataModel.DataModelDataContext();
        private DataModel.Usuario objUsuario = new DataModel.Usuario();


        public bool ValidarUsuario(string usuario,string pass)
        {
            int validar=(from p in contexto.Usuario
                             where (p.Usuario1==usuario && (p.Pass==pass))
                         select p);

        }
    }

This is the error of the image:

  

You can not implicitly convert the IQueryable type to int .

    
asked by PieroDev 22.04.2017 в 06:06
source

2 answers

5

What you are saying in your current query is that you select the users that match the conditions, that result will give you a System.Linq.IQueryable<DataModel.Usuario> , then the error comes when wanting to assign it to a int .

If you want to validate that a user exists, simply use the Count() method, if there is a record with those conditions, it will send you the result:

int validar = (from p in contexto.Usuario
               where (p.Usuario1 == usuario && (p.Pass == pass))
               select p).Count();

Another way to solve it, is changing the type int by var :

var validar = (from p in contexto.Usuario
               where (p.Usuario1 == usuario && (p.Pass == pass))
               select p);

Although I do not recommend it since you are leaving a little more work to the compiler to determine the type to which the result corresponds.

Another way to solve it is using lambda syntax:

int validar = contexto.Usuario.Where(t => t.Usuario1 == usuario && t.Pass == pass).Count();
    
answered by 22.04.2017 / 06:12
source
1

Hello, this can help you.

Eye with this line, I do not see that you use it, if you do not use it, do not instancies, you can remove it.

private DataModel.User ObjUser = new DataModel.User ();

   public bool ValidarUsuario(string usuario, string pass)
   {
      using(DataModel.DataModelDataContext contexto = new DataModel.DataModelDataContext())
      {
         int validar=(from p in contexto.Usuario
                         where (p.Usuario1==usuario && p.Pass==pass)
                     select p).Count();

             return validar == 0 ? false : true; 
      }
   }

Using will help you free the memory of the created context. I advise you to only instancies the objects when you are going to use them.

    
answered by 24.04.2017 в 22:17