首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET LINQ to SQL 查詢學號對應姓名並賦值 Label 完整教程

     編輯:程式設計綜合問答

場景

資料表 `Students`:`StudentID` (PK), `Name`, `Password`。已知學號查詢姓名,顯示在 `Label` 控件。

LINQ to SQL 實現步驟

  1. Visual Studio → 右鍵項目 → 添加 → 新項目 → **LINQ to SQL 類** (`.dbml`)。
  2. 從「伺服器資源管理器」拖拽 `Students` 表到設計面,生成 `DataContext` 及實體類 `Student`。
  3. 代碼查詢:

核心代碼 (C#)


// 頁面類
public partial class QueryStudent : System.Web.UI.Page {
    protected void btnQuery_Click(object sender, EventArgs e) {
        string inputId = txtStudentID.Text.Trim();
        if (string.IsNullOrEmpty(inputId)) {
            lblMessage.Text = "請輸入學號";
            return;
        }

        using (var db = new SchoolDataContext()) { // dbml 生成的 DataContext
            // 方案 1: FirstOrDefault (推薦,無結果返回 null 不拋異常)
            var student = db.Students.FirstOrDefault(s => s.StudentID == inputId);
            
            if (student != null) {
                lblName.Text = student.Name; // 直接賦值
                lblMessage.Text = "查詢成功";
            } else {
                lblName.Text = "";
                lblMessage.Text = "未找到該學號";
            }
        }
    }
}

關鍵點解析

方法行為適用場景
`FirstOrDefault(predicate)` 返回第一個匹配元素或 `null` (引用類型) / `default(T)` **預期 0 或 1 條** (PK/唯一索引查詢)
`SingleOrDefault(predicate)` 返回唯一匹配元素,**多於 1 條拋異常** 業務要求嚴格唯一性驗證
`Where(predicate).Select(s => s.Name).FirstOrDefault()` 僅投影所需字段,生成 `SELECT Name ...` SQL 大表優化,減少網絡傳輸

Entity Framework Core (現代替代) 寫法


// DbContext 注入 (ASP.NET Core DI)
public class QueryModel : PageModel {
    private readonly SchoolContext _db;
    public QueryModel(SchoolContext db) => _db = db;

    [BindProperty] public string InputId { get; set; }
    public string StudentName { get; set; }
    public string Message { get; set; }

    public void OnPost() {
        StudentName = _db.Students
            .Where(s => s.StudentID == InputId)
            .Select(s => s.Name)
            .FirstOrDefault() ?? "";
        Message = string.IsNullOrEmpty(StudentName) ? "未找到" : "成功";
    }
}
```razor @Model.Message ```

常見錯誤避坑

  • **未調用 `.ToList()` / `.FirstOrDefault()` 直接賦值 `IQueryable` 給 Label** → Label 顯示查詢表達式字符串而非結果。
  • **字符串比較大小寫敏感**:SQL Server 預設不區分大小寫,但 `==` 在 C# 區分,建議 `.Where(s => s.StudentID.Equals(inputId, StringComparison.OrdinalIgnoreCase))`。
  • **連接字符串錯誤** → `web.config` / `appsettings.json` 確認 `Data Source`、認證方式 (Windows/SQL)。
  • **未處理 `null`** → `lblName.Text = student?.Name ?? "未知";` (C# 6+)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved