Create Tables on runtime in EF Core

ⅰ亾dé卋堺 提交于 2019-12-09 05:54:44

问题


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:


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();



回答2:


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



来源:https://stackoverflow.com/questions/38532764/create-tables-on-runtime-in-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!