標籤:style blog io ar color sp on 檔案 資料
Code First 代碼優先。
上代碼:
建立你需要的資料模型(也可以認為是你需要的資料表):
namespace CodeFirstDemo.Models{ public class Student { public int Id { get; set; } public string Name { get; set; } } public class Teacher { public int Id { get; set; } public string Name { get; set; } }}
建立CodeFirstDB類,繼承自DbContext類。(注意引入System.Data.Entity命名空間的引用):
namespace CodeFirstDemo.Models{ public class CodeFirstDB:DbContext { public DbSet<Student> Student { get; set; } public DbSet<Teacher> Teacher { get; set; } }}
資料庫建立:
1.播種資料庫。
2.為了保證資料庫與模型同步(暫不考慮資料移轉的問題),在程式啟動每次啟動時重新建立資料庫(僅當檢測到模型改變時建立)
protected void Application_Start() { //當程式每次啟動時,檢測到模型改變則重新建立資料庫 Database.SetInitializer(new CodeFirstDemo()); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); }
/// <summary> /// 播種資料庫 /// </summary> public class CodeFirstDemo : DropCreateDatabaseAlways<CodeFirstDB> { protected override void Seed(CodeFirstDB context) { context.Student.Add(new Student { Id = 1, Name = "小明" }); context.Teacher.Add(new Teacher { Id = 1, Name = "老王" }); base.Seed(context); } }
程式調用:
public ActionResult Index() { CodeFirstDB db = new CodeFirstDB(); ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; var data = db.Student.ToList(); return View(); }
調用完成後,在你的App_Data檔案夾中查看結果。
注意:如果要為欄位賦值預設值。在預設建構函式中進行。
MVC學習之 Code First