0

I am trying to retrieve a string value from SQL server database, i am working on C# project and i am using LINQ to SQL. this is my code snippet

using (AlHayatEntities entity = new AlHayatEntities())
{
    var query = from o in entity.users
                where o.userName == "" + txtUsername.Text && o.password == "" + txtPassword.Text
                select o.role;
    MessageBox.Show(query + "");
}

and this is what the table is

id  | userName | password | role
1     shareef    123        admin

I want the message to print "admin" out, but it does not.

Igor
  • 60,821
  • 10
  • 100
  • 175
sh.alawneh
  • 639
  • 5
  • 13
  • Do `MessageBox.Show(query.First());` – Igor Jan 25 '17 at 18:33
  • 2
    Possible duplicate of [c# LINQ: how to retrieve a single result](http://stackoverflow.com/questions/6015081/c-sharp-linq-how-to-retrieve-a-single-result) – Eugene Podskal Jan 25 '17 at 18:33
  • 1
    Whats up with `"" + ` (all 3 of them)? Remove them, they are not necessary. – Igor Jan 25 '17 at 18:34
  • @lgor it is the same, no difference – sh.alawneh Jan 25 '17 at 18:34
  • 6
    **Do not store plain text passwords**, ever. [Learn the proper techniqe here](http://stackoverflow.com/q/1054022/335858), and use it in your designs. – Sergey Kalinichenko Jan 25 '17 at 18:35
  • `First()` will either throw an exception if there is nothing returned OR it will print out a role. If the role value in your table is empty only then could "nothing" happen. So if the message box is empty then the value of `role` is too. – Igor Jan 25 '17 at 18:38

1 Answers1

0

The result of a collection is an IQueryable in this case, since you have a single column it would be an IQueryable.

You could modify your code, like this.

 using (AlHayatEntities entity = new AlHayatEntities())
 {
     var result = (from o in entity.users
                 where o.userName == txtUsername.Text 
                         && o.password ==  txtPassword.Text
                 select o.role).FirstOrDefault();
     MessageBox.Show(result);
 }

I also removed the various "" items that were in your example, as they are not needed as part of the solution.

Another option, is to follow the query format, and then call FirstOrDefault when you display it. Like the below

 using (AlHayatEntities entity = new AlHayatEntities())
 {
     var query = from o in entity.users
                 where o.userName == txtUsername.Text 
                         && o.password ==  txtPassword.Text
                 select o.role;
     MessageBox.Show(query.FirstOrDefault());
 }

You could also use .First(), but that call requires that the result have an entry. If there is a chance that you don't have a record you wouldn't want to use it.

Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173