Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 562
pancake Avatar asked Sep 24 '12 08:09

pancake


2 Answers

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.

like image 89
Pranay Rana Avatar answered Oct 10 '22 18:10

Pranay Rana


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

// get user from query
// If SingleOrDefault is not supported (<4.0) use FirstOrDefault instead. 
// Thanks Tim Schmelter
var user = query.SingleOrDefault(); 

if (user != null)
{
    Session["UserID"] = user.UserID;                 
    Response.Redirect("Edit.aspx");
}
else
{
    LabelError.Text = "Error try again";
}
like image 41
Paul Fleming Avatar answered Oct 10 '22 16:10

Paul Fleming