如何通过LINQ结合Session从Basic_Detail表获取已登录用户数据?
Context
I have defined the following ViewModel that includes two data tables: Account_Details (for login validation) and Basic_Details (from which data needs to be fetched via Session after login):
public class BasicAccountView { public Account_Details Account_Details { get; set; } public Basic_Details Basic_Details { get; set; } }
Here's my login code, which stores the user ID, name, and email in corresponding Session variables after successful login:
public ActionResult Index(Account_Details log) { var obj = db.Account_Details.Where(u => u.Name.Equals(log.Name) && u.Password.Equals(log.Password)).FirstOrDefault(); Session["Account"] = log; if (obj != null) { Session["loginid"] = obj.U_ID; Session["name"] = obj.Name; Session["email"] = obj.Email; return RedirectToAction("Verify"); } else { return View(); } }
Question
How can I use LINQ to fetch the corresponding data for the currently logged-in user from the Basic_Details table?
Solution
Since you've already stored the user's U_ID in Session["loginid"] after a successful login, this is the key identifier you'll use to match records in the Basic_Details table. Here's a step-by-step implementation:
Validate and retrieve the user ID from Session
First, always check if the Session is valid (to avoid null reference errors or unauthorized access). Then cast the stored ID to its correct data type (I'm assumingU_IDis an integer here—adjust if it's a string/Guid):if (Session["loginid"] == null) { // Redirect back to login if session is expired or invalid return RedirectToAction("Index"); } int userId = Convert.ToInt32(Session["loginid"]);Fetch matching data from Basic_Details using LINQ
Use the retrieveduserIdto query the table. UseFirstOrDefault()if each user has exactly one record inBasic_Details, orToList()if multiple records exist for a single user:// Get a single matching record for the logged-in user var userBasicDetails = db.Basic_Details.Where(b => b.U_ID == userId).FirstOrDefault(); // Use this instead if multiple records are expected: // var userBasicDetailsList = db.Basic_Details.Where(b => b.U_ID == userId).ToList();Populate your ViewModel (optional but recommended)
Since you have theBasicAccountViewViewModel, you can combine the account details (from Session or re-fetched) and basic details into it for use in your view:public ActionResult Verify() { // Validate session first if (Session["loginid"] == null) { return RedirectToAction("Index"); } int userId = Convert.ToInt32(Session["loginid"]); // Fetch basic details via LINQ var basicDetails = db.Basic_Details.Where(b => b.U_ID == userId).FirstOrDefault(); // Retrieve account details from Session (or re-fetch from DB for freshness) var accountDetails = (Account_Details)Session["Account"]; // Populate the ViewModel var viewModel = new BasicAccountView { Account_Details = accountDetails, Basic_Details = basicDetails }; return View(viewModel); }
Quick Notes
- Always validate Session state before accessing its values to prevent runtime errors.
- If
U_IDis a non-integer type (likeGuid), adjust the casting logic (e.g.,Guid userId = Guid.Parse(Session["loginid"].ToString())). - For long-term projects, consider using ASP.NET Identity instead of manual Session management for better security and built-in authentication features.
内容的提问来源于stack exchange,提问作者Ali Raza

