我正在使用asp.net core 2和ef core 2开发一个API项目。当我每次想要删除所有表然后创建时进行迁移时,我想只包含更改。
public class TicketingContext : DbContext
{
public TicketingContext(DbContextOptions<TicketingContext> options) : base(options)
{
Database.Migrate();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Country> Countries { get; set; }
public DbSet<TZone> TZones { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<Point> Points { get; set; }
public DbSet<Bus> Buses { get; set; }
}
这是我的启动类和DesignTimeDbContextFactory
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, TicketingContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
这是 DesignTimeDbContextFactory实现
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<TicketingContext>
{
public TicketingContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<TicketingContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new TicketingContext(builder.Options);
}
}
答案 0 :(得分:1)
在Startup.cs中编辑Configure方法。将TicketingContext添加为参数:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, TicketingContext context)
{
...
context.Database.Migrate();
}