You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过LINQ结合Session从Basic_Detail表获取已登录用户数据?

How to retrieve logged-in user's data from Basic_Details table with LINQ?

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:

  1. 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 assuming U_ID is 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"]);
    
  2. Fetch matching data from Basic_Details using LINQ
    Use the retrieved userId to query the table. Use FirstOrDefault() if each user has exactly one record in Basic_Details, or ToList() 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();
    
  3. Populate your ViewModel (optional but recommended)
    Since you have the BasicAccountView ViewModel, 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_ID is a non-integer type (like Guid), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:08:07