新建数据库
create database mockstu
新建web项目
安装Microsoft.EntityFrameworkCore.SqlServer
包
设置连接字符串
新建model
using MockStuWeb.Models.EnumTypes;
using System.ComponentModel.DataAnnotations;
namespace MockStuWeb.Models
{
/// <summary>
/// 学生类
/// </summary>
public class Student
{
/// <summary>
/// 唯一标识
/// </summary>
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
[Display(Name = "名字")]
[Required(ErrorMessage = "请输入名字"), MaxLength(50, ErrorMessage = "名字的长度不能超过50个字符")]
public string? Name { get; set; }
/// <summary>
/// 主修课程
/// </summary>
[Required(ErrorMessage ="请选择主修课程")]
[Display(Name = "主修课程")]
public MajorEnum? Major { get; set; }
/// <summary>
/// 邮箱
/// </summary>
[Display(Name = "邮箱")]
[RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", ErrorMessage = "邮箱的格式不正确")]
[Required(ErrorMessage = "请输入邮箱地址,它不能为空")]
public string? Email { get; set; }
}
}
新建dbContenxt
using Microsoft.EntityFrameworkCore;
using MockStuWeb.Models;
namespace MockStuWeb.Infrastructure;
public class AppDbContext:DbContext
{
/// <summary>
/// 构造函数注入
/// </summary>
/// <param name="options"></param>
public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
{
}
public DbSet<Student> Students{get;set;}
}
program.cs中使用
builder.Services.AddDbContextPool<AppDbContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("MockStudentDBConnection"));
});
安装dotnet-ef
dotnet tool install --global dotnet-ef
创建迁移
cd .\MockStuWeb\
dotnet ef migrations add InitialCreate --namespace .\MockStuWeb.csproj --output-dir Migrations
安装Microsoft.EntityFrameworkCore.Tools
,顺便升级一下sql server包
需要改代码
更新到数据库中
dotnet ef database update InitialCreate
启用种子数据
Infrastructure下新建ModelBuilderExtensions
using Microsoft.EntityFrameworkCore;
using MockStuWeb.Models;
using MockStuWeb.Models.EnumTypes;
namespace MockStuWeb.Infrastructure;
public static class ModelBuilderExtensions
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasData(
new Student
{
Id = 2,
Name = "张三",
Major = MajorEnum.ComputerScience,
Email = "zhangsan@52abp.com"
}
);
}
}
AppDbContext添加如下代码
/// <summary>
/// 模型创建的时候
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Seed();
}
添加迁移记录并更新
dotnet ef migrations add AlterStudentsSeedData --namespace .\MockStuWeb.csproj --output-dir Migrations
dotnet ef database update AlterStudentsSeedData
进行回退
dotnet ef migrations list
dotnet ef migrations remove -f
只能手动修改一下代码
建立表格的代码注释掉
单条数据也可以这么写
进行回退
dotnet ef migrations list
dotnet ef migrations remove -f
dotnet ef database update InitialCreate
把这次迁移的文件删除即可
参考