MVC學習之資料庫開發模式:程式碼優先例項介紹
阿新 • • 發佈:2021-01-02
資料庫開發模式之程式碼優先主要有以下幾步:
1、在Models資料夾中建立需要的表所對應的類
2、建立資料上下文類
3、在webConfig檔案中配置資料庫連線節點
4、新增控制器和相應的檢視檔案
5、在控制器的動作中建立資料上下文例項,通過例項操作資料庫資料
具體步驟如下所示:
1、在Models資料夾中建立所需表對應的類
namespace CodeFirst.Models
{
public class book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string Price { get; set; }
}
}
2、建立資料上下文類
/// <summary>
/// 建立一個數據上下文
/// </summary>
public class BooksDBContext : DbContext
{
public DbSet<book> books { get; set; }
}
到此,Models資料夾下的book類如下所示:注意:books就是建立好的資料庫裡面的book表的名稱
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace CodeFirst.Models
{
public class book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string Price { get; set; }
}
/// <summary>
/// 建立一個數據上下文
/// </summary>
public class MyBooks : DbContext
{
public DbSet<book> books { get; set; }
}
}
3、在webConfig檔案中配置資料庫連線節點
<connectionStrings>
<add name="繼承資料上下文的那個類的名字【MyBooks】" connectionString="Data Source=這裡是伺服器名稱;Initial Catalog=給資料庫取的名字【Books】;User ID=這裡是資料庫的登入名;Password=這裡是
資料庫登入密碼" providerName="System.Data.SqlClient"/> </connectionStrings>
注意:我用漢字說明的地方,自己根據自己資料庫的配置做出修改即可【name屬性要和上面建立的資料上下文類一樣,否則創建出來的資料庫名字就不是自己設定的名字而是這樣一串:專案名稱.Models.資料上下文類名】
4、新增控制器和相應的檢視檔案
5、在控制器的動作中建立資料上下文例項,通過例項操作資料庫資料
using CodeFirst.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CodeFirst.Controllers
{
public class BooksController : Controller
{
//
// GET: /Books/
//MyBooks是繼承DbContext資料上下文的那個類也是web.config檔案中新增的連線資料庫字串的名字【name屬性的值】
private MyBooks dbBooks = new MyBooks();
public ActionResult Index()
{
return View(dbBooks.books.ToList());
}
}
}
重新生成,執行結果展示:
資料庫:
新增資料後頁面展示: