I am developing an API project with asp.net core 2 and ef core 2. when I am doing migration every time it wants to drop all tables and then create, but I want only changes will be included.
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; }
}
Here is my startup class and 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();
}
}
And here is DesignTimeDbContextFactory implementation
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);
}
}
Edit Configure method in your Startup.cs. Add your TicketingContext as a parameter:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, TicketingContext context)
{
...
context.Database.Migrate();
}