MVC使用EntityFramework(EF)生成数据库模型

首先打开VS2013,新建Web项目mcc,使用MVC模板。

右击引用,管理NuGet程序包,安装EntityFramework。

在Model文件下新建类Employee,新增几个属性,比如:EmployeeId,FirstName,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 设置为主键。

在Web.Config里面设置数据库连接字符串

<add name="MyDBConnectString" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=SalesERPDAL;user id=sa;password=sa"/>

在根目录下新建文件夹DataAccessLayer,新建类SalesERPDAL,继承DbContext。

在 CodeFirst 模式,根据实体类生成对应数据库表。

public class SalesERPDAL : DbContext
    {
        public SalesERPDAL() : base("MyDBConnectString")//数据库连接字符串
        {
            this.Configuration.ProxyCreationEnabled = true;
            var aaa = new DbMigrationsConfiguration();//设置自动迁移属性
            aaa.AutomaticMigrationsEnabled = true; 
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().ToTable("TblEmployee");//设置生成对应数据库表的名称
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Employee> Employees { get; set; }
    }

  

此时,基本设置完成,开始使用命令创建数据库,生成表。

打开工具-NuGet程序包管理器-程序包管理器控制台

输入命令:Enable-Migrations ,允许迁移。

输入命令:Enable-Migrations -ContextTypeName aaa.DataAccessLayer.SalesERPDAL,指定迁移类型。

输入命令:Add-Migration ,将挂起的模型更改写入基于代码的迁移。

Name:update(随意输入)

输入命令: Update-Database -Verbose,执行生成命令,创建数据库,更新表。

如上图,已经可以在数据库中查看到对应的表,可以插入数据,进行获取验证了。

原文地址:https://www.cnblogs.com/mxw-top/p/5780427.html