EF Core Migrations
创建一个WebAPI.Migrations
dotnet new webapi -n WebAPI.Migrations
Program.cs
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using DataAccess;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<MusicCollectionDb>(
options =>options.UseSqlServer(builder.Configuration.GetConnectionString("MusicDbConnection"),b => b.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName)));
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.Run();
其他数据库
var msSqlConnection = builder.Configuration.GetConnectionString("MsSqlConnection");
options.UseSqlServer(msSqlConnection, b => b.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName));
var sqliteConnection = builder.Configuration.GetConnectionString("SqliteConnection");
options.UseSqlite(sqliteConnection, b => b.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName));
var mySqlConnection = builder.Configuration.GetConnectionString("MySqlConnection");
//MySql需要传入版本,ServerVersion.AutoDetect根据连接字符串自动获取
options.UseMySql(mySqlConnection, ServerVersion.AutoDetect(mySqlConnection), b => b.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName));
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MusicDbConnection": "Data Source=localhost;Initial Catalog=musicdb2;User ID=sa;Password=song2030..;Trust Server Certificate=True"
}
}
添加迁移文件
dotnet ef migraitons add init
dotnet ef database update
标签:core,builder,ef,migrations,var,using,Configuration,GetConnectionString,options
From: https://www.cnblogs.com/zhuoss/p/18473148