Question

Here's my query:

       var query = from d in db.Users
                    where user.UserName == d.UserName && user.Password == d.Password
                    select d;

Now I know for a fact that the query will either be null (if user credentials do not match) or only return one user. My problem now is that I want to access the variables of that one user. How do do that? I've tried using this line of code:

        foreach (var item in query)
        {
            Session["id"] = item.ID;
            Session["name"] = item.UserName;
            Session["type"] = item.Type;
        }

But it causes my program to crash (I know the query isn't null so that isn't the issue).

Was it helpful?

Solution

You can use SingleOrDefault to generally return null if the collection is empty, but it can also return something else if TSource defines something else as the default, so use with caution.

var user = (from d in db.Users
            where user.UserName == d.UserName && user.Password == d.Password
            select d).SingleOrDefault();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top