简体   繁体   中英

Create SQL Database From DBContext EF Core

My pc suddenly got sick and all the data are removed and no way to recover them.

I was working on several projects with .NET 5 using EF core 6 Database first approach.

I cloned my projects from GitHub to get them back but unfortunately I don't have a backup or SQL file for the database.

Is there any way to create the database from the dbContext in the .NET 5 project?

I do not quite understand the question, is perhaps meant something like this?

//creates an instance of the class where the "database" is
Database db = new Database();

//creates the database if it does not exist
db.Database.EnsureCreated();

You should probably use dbContext.Database.EnsureCreated();

With this your DataBase structure will be re-created from the model. Of course, there will be no data, just empty tables, indexes etc.

You can re-create the database structure with your existing model. But there is no way to recover the data

You can use this code in startup.cs file or program.cs '.net core 6'

`dbContext.Database.Migrate()`

This line will update database with all migrations which not applied on database

The fastest way was running these commands:

Add-Migration InitialCreate

and Then:

Update-Database

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