项目结构:
首先引用
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 DbSet Customers { 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 增加
有可能报错找不到程序集,需要再PropertyGroup节点添加指定运行版本
2.0.3
最终的配置文件如下:
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
View Code
cmd到QH.Data项目文件夹
生成迁移指令
dotnet ef migrations add initDB
更新到数据库
dotnet ef database update