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).

有帮助吗?

解决方案

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top