In my project I have 2 databases: one is my custom database and the other one is ApplicationDbContext
that Microsoft Identity
gives me.
In my Startup.cs
I have this code:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
ApplicationDbContext db, MyContext dbPSC)
{
// ...
db.Database.EnsureCreated();
db.Database.Migrate();
dbPSC.Database.EnsureCreated();
dbPSC.Database.Migrate();
}
I don't know when there is a migration to migrate, right? Then, I have 2 errors:
- the migration for
ApplicationDbContext
raises an error every time the application starts apart from the first time - the migration for my context seems fine
What is the best practise to use? Is it necessary to call the migration for ApplicationDbContext
?
Update
I have removed the Migration
folder. Then, changed the Startup.cs
like
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
ApplicationDbContext db, MyContext dbPSC)
{
// ...
db.Database.EnsureCreated();
dbPSC.Database.EnsureCreated();
}
but when the application starts, it doesn't create any tables at all. AuditDbContext
is because I use Audit.net
public class MyContext : AuditDbContext
{
public MyContext(DbContextOptions<MyContext> options) : base(options) { }
public DbSet<Message> Messages { get; set; }
public DbSet<AuditMessage> Audit_Messages { get; set; }
#region Common Tables
public DbSet<Country> Countries { get; set; }
public DbSet<AuditCountry> Audit_Countries { get; set; }
#endregion
#region Seed
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Seed();
}
#endregion
}
Update #2
I tried another solution but it doesn't work. The solution is to use RelationalDatabaseCreator
like the following code
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
ApplicationDbContext db, MyContext dbPSC)
{
// ...
db.Database.EnsureCreated();
dbPSC.Database.EnsureCreated();
RelationalDatabaseCreator databaseCreator =
(RelationalDatabaseCreator)context.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();
}
As the Migrate()
, the first time the app runs it creates the tables but the second time it raises an error because the tables are already exist in the database.