.Net 6 使用Code Frist EF简单数据迁移
1.定义 EF Code First 上下文 StuContext 类 和一个类 作为模型
映射字段
using System.Data.Entity; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity.Infrastructure; namespace MigrationsDemo { public class StuContext : DbContext { public DbSet<Student> Students { get; set; } }
public class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Sex { get; set; }
}
}
2. Nuget包下载

安装包为6.0版本即可 5.0版本可能报错
3.配置链接字符串
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
//配置链接字符串
"ConnectionStrings": {
"sql": "Data Source=.;Initial Catalog=Db1208;Integrated Security=True"
}
}
4. 在Program.cs中添加DbContext服务
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//.添加DbContext服务
builder.Services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sql")));
5.在工具中 选择 Nuget包管理器=》程序包管理器控制台





浙公网安备 33010602011771号