Create Tables on runtime in EF Core

2020-05-26 16:41发布

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 ?

2条回答
家丑人穷心不美
2楼-- · 2020-05-26 17:13

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();
查看更多
Melony?
3楼-- · 2020-05-26 17:25

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

查看更多
登录 后发表回答