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.
You should specify which DbContext you use:
dotnet ef migrations add ArbitraryMigrationName -c YourDbContextName