Asp.net Mvc Entity Framework Code First 数据库迁移

时间:2022-09-22 00:28:01

1、创建Mvc项目

2、安装Entity Framework

2.1、如下图打开程序包管理器控制台:

Asp.net Mvc Entity Framework  Code First  数据库迁移

2.2、输入命令Install-Package EntityFramework,即可安装EntityFramework,如下图:

Asp.net Mvc Entity Framework  Code First  数据库迁移

 

3、创建你的需要的实体类

我这里简单创建一个Student类,如下:

    public class Student
{
public int ID { set; get; }
public string Name { set; get; }
}

4、创建数据库上下文类(Database context)

新建类(我这里用SchoolContext命名),继承DbContext,如下:

.....
using System.Data.Entity.ModelConfiguration.Conventions;
using WebApplication1.Models;
......
public class SchoolContext: DbContext
{
public SchoolContext() : base("SchoolContext") { }

public DbSet<Student> Student { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//prevents table names from being pluralized(防止生成的数据库表名称是复数形式,如Students)
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}

public DbSet<Student> Student { get; set; }这句不能忘了加,这对应刚才建的Student类。

 

5、修改配置文件(Web.config)


在Web.config文件里添加代码:

<connectionStrings>
<add name="SchoolContext" connectionString="data source=.;initial catalog=SchoolDB;persist security info=True;user id=sa;password=123456;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>

 

6、在程序包管理器控制台执行迁移命令

6.1、输入enable-migrations,并执行,项目里会自动添加Migrations文件夹,并生成类文件Configuration.cs,如下:

internal sealed class Configuration : DbMigrationsConfiguration<WebApplication1.DAL.SchoolContext>
{
public Configuration()
{
AutomaticMigrationsEnabled
= false;
}

protected override void Seed(WebApplication1.DAL.SchoolContext context)
{
// This method will be called after migrating to the latest version.

// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}

 

6.2、输入命令:add-migration "第一次迁移"

后面的汉字可以自定义。

项目会生成201611010701013_第一次迁移.cs文件,如下:

public partial class 第一次迁移 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Student",
c
=> new
{
ID
= c.Int(nullable: false, identity: true),
Name
= c.String(),
})
.PrimaryKey(t
=> t.ID);

}

public override void Down()
{
DropTable(
"dbo.Student");
}
}

6.3、输入命令update-database即可在数据库看到数据库了。

 

 

参考文档:https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application