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

ASP.NET MVC (Database First) 從本地資料庫讀取數據並顯示至頁面完整流程

     編輯:程式設計綜合問答

架構分層說明

Controller (控制器) → Service/Repository (業務/數據訪問) → Entity (實體類) → View (視圖)

完整實現步驟 (VS 2019+ / .NET Framework 4.8 / EF 6)

1. 建立 EDMX 模型 (Database First)

  1. 專案右鍵 → Add → New Item → ADO.NET Entity Data Model
  2. 選擇 "EF Designer from database" → 配置連線字串 → 選取資料表/視圖/預存程序 → 完成
  3. 產生 YourDbContext (繼承 DbContext) 及實體類 (如 Product)

2. 建立 Repository (可選,簡化直接在 Controller 用 DbContext)

public class ProductRepository {
    private readonly YourDbContext _db = new YourDbContext();
    public IEnumerable GetAll() => _db.Products.ToList();
    public Product GetById(int id) => _db.Products.Find(id);
    // 單元測試時可改為介面 + 依賴注入
}

3. Controller 行為

public class ProductController : Controller {
    private readonly ProductRepository _repo = new ProductRepository();

    // GET: /Product
    public ActionResult Index() {
        var list = _repo.GetAll();
        return View(list);  // 強類型傳遞 IEnumerable
    }

    // GET: /Product/Details/5
    public ActionResult Details(int id) {
        var item = _repo.GetById(id);
        if (item == null) return HttpNotFound();
        return View(item);
    }
}

4. 視圖 (Razor 語法)

Index.cshtml (列表頁)

@model IEnumerable


        @foreach (var p in Model) {
            
        }
    
ID名稱價格操作
@p.Id @p.Name @p.Price.ToString("C") @Html.ActionLink("詳情", "Details", new { id = p.Id })

Details.cshtml (詳情頁)

@model YourNamespace.Models.Product

@Html.DisplayNameFor(m => m.Name)
@Html.DisplayFor(m => m.Name)
@Html.DisplayNameFor(m => m.Price)
@Html.DisplayFor(m => m.Price)

關鍵點總結

  • 連線字串 在 Web.config <connectionStrings> 維護,勿硬編碼
  • DbContext 生命週期:每請求一個實例 (上例簡化為字段,正式專案請用 DI 容器 AddScoped)
  • 延遲載入 vs 預先載入:導航屬性預設延遲載入,列表頁建議 .Include(p => p.Category) 避免 N+1 問題
  • 資料註釋驗證:實體類加 [Required], [StringLength(100)] 等,前端自動生成驗證

進階:分頁、排序、搜尋

public ActionResult Index(int page = 1, string keyword = "") {
    var query = _repo.GetAll().AsQueryable();
    if (!string.IsNullOrEmpty(keyword)) query = query.Where(p => p.Name.Contains(keyword));
    var paged = query.OrderBy(p => p.Id).Skip((page-1)*10).Take(10).ToList();
    ViewBag.Keyword = keyword;
    return View(paged);
}

總結

Database First 流程:EDMX → 實體/Context → Repository → Controller → 強類型 View。**核心在於「強類型模型傳遞」與「關注點分離」**,避免在 View 裡寫 SQL 或商業邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved