I know I can use the following command to add a new migration and create the database :
dotnet ef migrations add MigrationName -c DbContextName
dotnet ef database update -c DbContextName
but I need to create my database/tables on runtime.
First I tried to do that by overriding OnModelCreating but I failed. It returned me an error pointing out that the tables have not been created
Here is my dbcontext class
public class AimeLoggerContext : DbContext
{
public AimeLoggerContext(DbContextOptions<AimeLoggerContext> options)
: base(options)
{
Database.Migrate();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity("Aime.Logger.Loggers.Database.Model.Log", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("Datetime");
b.HasKey("Id");
b.ToTable("Logs");
});
base.OnModelCreating(modelBuilder);
}
public DbSet<Log> Logs { get; set; }
}
Any Idea ?
If you need to create you model tables also if in your DB there are some other tables you can use
Instead of
DbContext.Database.Migrate()
I should useDbContext.Database.EnsureCreated()
method.