Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Tables on runtime in EF Core

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 at 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; }
    }
like image 569
Ali Foroughi Avatar asked Jul 22 '16 18:07

Ali Foroughi


1 Answers

If you need to create you model tables also if in your DB there are some other tables you can use

RelationalDatabaseCreator databaseCreator = 
    (RelationalDatabaseCreator) context.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();
like image 187
bubi Avatar answered Oct 09 '22 23:10

bubi