Search code examples
c#asp.netlinqsessionlinq-to-entities

ASP.NET Session and LINQ


I have a question regarding a project I am working on at the moment.

I have this code:

 var query = from user in dwe.UsersTable
                        where user.LoginName.Equals(usernameBox.Text) && user.Password.Equals(pwBox.Text)
                        select user;

        if (query.Count() == 1)
        {
            Session["User"] = usernameBox.Text;                     
            Response.Redirect("Edit.aspx");
        }
        else
        {
            LabelError.Text = "Error try again";
        }
    }

In my "UsersTable" I have a coulmn named "UserID". I want to send the "userID" as a session to the redirected page (Edit.aspx) the userID must equal the result of comparression between Username and password.


Solution

  • you just need to write down

    var query = (from user in dwe.UsersTable 
                            where user.LoginName.Equals(usernameBox.Text) && 
                            user.Password.Equals(pwBox.Text)
                             select user).FirstOrDefault();
    
    if(query!=null)
    {
       Session["User"] = query.UserID; 
       Response.Redirect("Edit.aspx"); 
    }
    else
    {
       LabelError.Text = "Error try again";
    }
    

    No need to write donw code you have which use Count method instead of this just make use Of FirstOrDefault will give you the result easily.