MVC使用EntityFramework(EF)生成數(shù)據(jù)庫(kù)模型
首先打開(kāi)VS2013,新建Web項(xiàng)目mcc,使用MVC模板。
右擊引用,管理NuGet程序包,安裝EntityFramework。
在Model文件下新建類(lèi)Employee,新增幾個(gè)屬性,比如:EmployeeId,F(xiàn)irstName,LastName,Salary。
- public int EmployeeId { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public int Salary { get; set; }
引用using System.ComponentModel.DataAnnotations; 將EmployeeId 設(shè)置為主鍵。
在Web.Config里面設(shè)置數(shù)據(jù)庫(kù)連接字符串
<add name="MyDBConnectString" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=SalesERPDAL;user id=sa;password=sa"/>
在根目錄下新建文件夾DataAccessLayer,新建類(lèi)SalesERPDAL,繼承DbContext。
在 CodeFirst 模式,根據(jù)實(shí)體類(lèi)生成對(duì)應(yīng)數(shù)據(jù)庫(kù)表。
- public class SalesERPDAL : DbContext
- {
- public SalesERPDAL() : base("MyDBConnectString")//數(shù)據(jù)庫(kù)連接字符串
- {
- this.Configuration.ProxyCreationEnabled = true;
- var aaa = new DbMigrationsConfiguration();//設(shè)置自動(dòng)遷移屬性
- aaa.AutomaticMigrationsEnabled = true;
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Employee>().ToTable("TblEmployee");//設(shè)置生成對(duì)應(yīng)數(shù)據(jù)庫(kù)表的名稱(chēng)
- base.OnModelCreating(modelBuilder);
- }
- public DbSet<Employee> Employees { get; set; }
- }
此時(shí),基本設(shè)置完成,開(kāi)始使用命令創(chuàng)建數(shù)據(jù)庫(kù),生成表。
打開(kāi)工具-NuGet程序包管理器-程序包管理器控制臺(tái)
輸入命令:Enable-Migrations ,允許遷移。
輸入命令:Enable-Migrations -ContextTypeName aaa.DataAccessLayer.SalesERPDAL,指定遷移類(lèi)型。
輸入命令:Add-Migration ,將掛起的模型更改寫(xiě)入基于代碼的遷移。
Name:update(隨意輸入)
輸入命令: Update-Database -Verbose,執(zhí)行生成命令,創(chuàng)建數(shù)據(jù)庫(kù),更新表。
如上圖,已經(jīng)可以在數(shù)據(jù)庫(kù)中查看到對(duì)應(yīng)的表,可以插入數(shù)據(jù),進(jìn)行獲取驗(yàn)證了。