Asp.net Core 2 migration not working correctly

asp.net-core entity-framework-core

Question

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);
    }
}
1
0
10/12/2017 5:58:25 AM

Popular Answer

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();
}
1
10/10/2017 9:45:04 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow