Auto Create Database in Entity Framework Core

How to auto create database on first run?

If you have created the migrations, you could execute them in the Startup.cs as follows.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
}

...

This will create the database and the tables using your added migrations.

If you're not using Entity Framework Migrations, and instead just need your DbContext model created exactly as it is in your context class at first run, then you can use:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}

...

Instead.

If you need to delete your database prior to making sure it's created, call:

context.Database.EnsureDeleted();

Just before you call EnsureCreated()

Adapted from: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html?highlight=entity

Auto Create database using EF Core

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

Create Database on Runtime - Entity FrameWork Code-First

I have found the solution, I should use raw.SetProvider(new SQLite3Provider_e_sqlite3()); in OnConfiguring:

public MyDataContext(string path, bool create = true)
{
FilePath = path;
if (create)
{
Database.EnsureDeleted();
Database.EnsureCreated();
}
}

protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
{
optionbuilder.UseSqlite($"Data Source={FilePath}");
raw.SetProvider(new SQLite3Provider_e_sqlite3());
}

Auto Create Database Tables from Objects, Entity Framework

is it possible to generate tables from objects created in C#?

Yes it is possible. Did you happen to create the Database manually in Management Studio before running the Code? That could be your problem. With Code First, the default convention is to create the database if it does not exist already. If the database already exists (even without the tables) then it is going to just use the existing database (but it won't try and create the tables).

You can either delete the database and try and run the code again to see if it will create it for you or put the following line in Global.asax:

Database.SetInitializer(new DropCreateDatabaseAlways<YourDbContextHere>());

Once it has run then I would suggest changing that line to:

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourDbContextHere>());

These namespaces are defined in System.Data.Entity

The DbContext class also exposes a Database property which defines the following useful methods:

Delete()
Create()
CreateIfNotExists()

So if you defined your class like so:

public class MyContext : DbContext {}

You can construct an instance like so:

MyContext db = new MyContext();
db.Database.Delete();
db.Database.Create();

Entity Framework Core automatically inserts double quotes in Oracle database

In the end I understood the problem wasn't only for Identity Provider tables.

So I've implemented linq2db and linqToDb.Identity and made it work by putting

OracleTools.DontEscapeLowercaseIdentifiers = false;

in the ConfigureServices method of Startup.cs.

Quick note: LinqToDb.Identity NuGet package is stuck on a May 2021 release which is incompatible with recent Linq2DB packages due to various missing references to this (e.g. this.GetTable) in the IdentityDataConnection class, so you might as well download the source code and include it in your project (or make a class library out of it) and fix the class.

Repo link: https://github.com/linq2db/LinqToDB.Identity

Updating a SQLite Database to reflect a change to the model with Entity Framework Core and .NET 6

Run the Add-Migration AddUrl command in Package Manager Console. The Add-Migration command checks for changes since your last migration and scaffolds a new migration with any changes that are found. We can give migrations a name; in this case we are calling the migration ‘AddUrl’. The scaffolded code is saying that we need to add a Url column, that can hold string data, to the dbo.Blogs table. If needed, we could edit the scaffolded code but that’s not required in this case.

Run the Update-Database command in Package Manager Console. This command will apply any pending migrations to the database. Our InitialCreate migration has already been applied so migrations will just apply our new AddUrl migration. Tip: You can use the –Verbose switch when calling Update-Database to see the SQL that is being executed against the database.

Dealing with Model Changes



Related Topics



Leave a reply



Submit