项目结构:
首先引用
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
增加类DesignTimeDbContextFactory
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory{ public QHContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder(); //builder.UseSqlServer("Server=(localdb)\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Light;"); builder.UseSqlServer("Server=***;Database=**;User ID=**;Password=**;Trusted_Connection=false;Connect Timeout=120;MultipleActiveResultSets=True;"); return new QHContext(builder.Options); } }
QHContext 类
public class QHContext : DbContext { public QHContext(DbContextOptions options) : base(options) { } public DbSetCustomers { get; set; } public DbSet Orders { get; set; } public DbSet OrderItems { get; set; } public DbSet Products { get; set; } public DbSet ProductItems { get; set; } public DbSet Users { get; set; } public DbSet BuckleRecords { get; set; } public DbSet CustomerRelations { get; set; } public DbSet OrderLogs { get; set; } public DbSet RebateRecords { get; set; } public DbSet Recharges { get; set; } public DbSet Withdraws { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //var builder = new ConfigurationBuilder() // .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); //var configuration = builder.Build(); //string connectionString = configuration.GetConnectionString("MyConnection"); //optionsBuilder.UseMySQL(connectionString); } protected override void OnModelCreating(ModelBuilder builder) { //builder.Entity ().HasKey(m => m.CustomerId); builder.Entity ().ToTable("Customer"); builder.Entity ().ToTable("BuckleRecord"); builder.Entity ().ToTable("CustomerRelation"); builder.Entity ().ToTable("Order"); builder.Entity ().ToTable("OrderItem"); builder.Entity ().ToTable("OrderLog"); builder.Entity ().ToTable("Product"); builder.Entity ().ToTable("ProductItem"); builder.Entity ().ToTable("RebateRecord"); builder.Entity ().ToTable("Recharge"); builder.Entity ().ToTable("User"); builder.Entity ().ToTable("Withdraw"); base.OnModelCreating(builder); } }
编辑Qh.Data项目的csproj 增加
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" /></ItemGroup>有可能报错找不到程序集,需要再PropertyGroup节点添加指定运行版本
<RuntimeFrameworkVersion>2.0.3</RuntimeFrameworkVersion>
最终的配置文件如下:
netcoreapp2.0 2.0.3 ..\lib\CZY.Framework.dll C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.configuration\2.0.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll
cmd到QH.Data项目文件夹
生成迁移指令
dotnet ef migrations add initDB
更新到数据库
dotnet ef database update
如果:执行命令总是提示 未找到与命令“dotnet-ef”匹配的可执行文件
增加节点: