Create Tables on runtime in EF Core

entity-framework-core

Question

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 ?

1
11
7/22/2016 6:31:54 PM

Accepted Answer

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();
15
8/21/2017 11:24:26 AM

Popular Answer

Instead of DbContext.Database.Migrate() I should use DbContext.Database.EnsureCreated() method.



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