简体   繁体   中英

Auto Create database using EF Core

I'm using EF Core in my Winforms application but I can't generate database automatically without migrations.

I read this articles but It is for asp.net core: auto create database in Entity Framework Core

My DbContext :

    public DbSet<Users> Users { get; set; }
    public DbSet<Accounts> Acc { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["FreeAcc"].ConnectionString);
    }

Edit: I'm using localdb

You can use context.Database.EnsureCreated() to create the database if it doesn't exist.

EnsureCreated will create the database if it doesn't exist and initialize the database schema. If any tables exist (including tables for another DbContext class), the schema won't be initialized.

EnsureCreated is part of EF Core in Microsoft.EntityFrameworkCore , it's not exclusive to ASP.NET Core.

I suggest you call EnsureCreated when your application starts up or just before you use your DbContext .

EF Core Create and Drop APIs Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM