Home > Software design >  How to query a Dbset to find one specific object via LINQ?
How to query a Dbset to find one specific object via LINQ?

Time:09-21

Im trying to acess my database via the application db context class that has dbsets of each table, my objetive is to retrieve a field from the database from a specific user that is inserted on a input on login, however im unsure as to how i can query the database via LINQ to get the specific field from the user

 //Search if username exists on database(working)
            var user = _context.User.Where(a => a.Username == Credential.Username).FirstOrDefault();
            //Get the salt from that user(not working)
            var salt = _context.User.Where(a => a.Username == Credential.Username).Select(a => a.Salt);
            //Get the hash from that user(also not working)
            var hash = _context.User.Where(a => a.Username == Credential.Username).FirstOrDefault();

            

            if (user!= null && Credential.Username == user.Username && Credential.Password =="password")
            {

My objective is to first check if the user exists via comparing the inputed username to the existing users on the database, then getting his salt, to salt his input and hash it to compare it to the existing hashes on my database, but im not sure how to query the DBset via LINQ is there any recommended way to do these queries?

CodePudding user response:

ok i think i understand now, i was grabbing the whole user from the database, not just the username so i can use this whole user object to get the other fields i need, by getting a user that has a username = to the login input that guarantees the user is correct i tried limiting the login to the hash on the database and changing the if(Credential.password= salt) and the login works so i assume its getting the right value i tested other values and its not working so it was just me not understanding what i was grabbing from that query.

CodePudding user response:

In the following case, you are writing a query but not executing it. If you check salt data type, you will find it of type IQueryable.

var salt = _context.User.Where(a => a.Username == Credential.Username).Select(a => a.Salt);

To actually querying the database, call FirstOrDefault() as the following:

var salt = _context.User.Where(a => a.Username == Credential.Username).Select(a => a.Salt).FirstOrDefault();

In the following case, the result of the statement is of type User since you are not selecting the hash .Select(a => a.Hash) as the following:

var hash = _context.User.Where(a => a.Username == Credential.Username).Select(a => a.Hash).FirstOrDefault();
  • Related