前言:
用到的迁移命令:
Add-Migration test 生成迁移文件命令,test是迁移文件名称
Update-Database 迁移更新到数据库
用到的NuGet包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
一.创建项目,安装需要依赖包
创建完成后安装NuGet包
搜索安装
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
二. 创建表实体类和上下文类
- 创建Context文件夹并创建两个类,一个表实体类City,一个用于绑定上下文类DemoContext
- City表类添加几个字段,全部代码如下
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication1.Context
{
public class City
{
[Key]
public int Id { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string Name { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string AreaCode { get; set; }
}
}
- 在上下文类DemoContext注册刚才的City表类,全部代码如下
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Context
{
public class DemoContext : DbContext
{
public DbSet<City> Cities { get; set; }
public DemoContext(DbContextOptions<DemoContext> option) : base(option)
{
}
}
}
三. 注册服务,连接数据库,开始迁移
1.在appsettings.json添加数据库连接串
"ConnectionStrings": {
"DbConnectionString": "Data Source = localhost;Initial Catalog = myDataBasetest;User Id = sa;Password = 123456;"
}
2. 在Program注册服务,使用连接配置字符串 连接数据库
builder.Services.AddDbContext<DemoContext>(option =>
{
string DbConnectionString = builder.Configuration.GetConnectionString("DbConnectionString");
option.UseSqlServer(DbConnectionString);
});
3. 打开程序包管理器控制台,使用命令Add-Migration test生成迁移文件,准备开始迁移
test是迁移文件名称
生成迁移文件成功后可以查看
4.使用Update-Database 命令开始迁移,更新表实体类到数据库
查看数据库,迁移成功