3

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

marc_s
760k186 gold badges1.4k silver badges1.5k bronze badges
asked Aug 27, 2020 at 20:45
3
  • 1
    You do need Migrations to generate the Db automatically. Otherwise you need to create the schema yourself. Commented Aug 27, 2020 at 20:49
  • 1
    You could try using context.Database.EnsureCreated(). More information here Commented Aug 27, 2020 at 20:52
  • @Shoejep I didn't know about those APIs and been having some experience in EF Core recently. I stand corrected. Commented Aug 27, 2020 at 20:56

1 Answer 1

1

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

answered Aug 28, 2020 at 17:40
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.