Database migration with two context in Asp.Net Core (SQL Server on Docker)

asp.net-core database-migration docker entity-framework entity-framework-core

Question

I have two Context in my Application. One in WebApi Project -> ApiContext (inherited from IdentityDbContext) and another one in Infrastructure -> Context.

I use Official images for Microsoft SQL Server on Linux for Docker Engine (microsoft/mssql-server-linux).

I wrote a DbFactory. Below you can find my codes.

ApiContext:

internal class ApiContext : IdentityDbContext<ApplicationUser>
{
    public ApiContext(DbContextOptions<ApiContext> options) : base(options)
    {
        Database.EnsureDeleted();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

Context

internal class Context : DbContext
{
    public Context(DbContextOptions<Context> options) : base(options)
    {
        Database.EnsureCreated();
    }

    public DbSet<Reservation> Reservations { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Table>().ToTable("Table");
    }
}

In my infrastructure project, I have as I said DbFactory

public class DesignTimeDbContextFactory<T> : IDesignTimeDbContextFactory<T>
    where T : DbContext
{
    public T CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var builder = new DbContextOptionsBuilder<T>();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        builder.UseSqlServer(connectionString);
        var dbContext = (T)Activator.CreateInstance(
            typeof(T),
            builder.Options);
        return dbContext;
    }
}

and

internal class ContextDesignTimeDbContextFactory : DesignTimeDbContextFactory<Context>
{
}

and in WebApi project

internal class ApiContextDesignTimeDbContextFactory : DesignTimeDbContextFactory<ApiContext>
{
}

I would like to use entity framework core migration. When I run

dotnet ef migrations add InitialCreate

in ApiProject (using cmd) I get

More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

Could you please tell me how can I handle database migration with two contexts on Asp.Net Core 2.0 and EntityFrameworkCore 2 and docker.

1
2
4/15/2018 8:10:36 AM

Accepted Answer

You should specify which DbContext you use:

dotnet ef migrations add ArbitraryMigrationName -c YourDbContextName
1
9/29/2017 6:10:48 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