简体   繁体   中英

How to update database using entity framework without migration history

I have an application in a running state and working fine , I have my project folder too.

Now I have updated and create some more tables inside that project . Unfortunately I've deleted the migrations files inside migration folder .

Now I have a database and inside migration history table I have recently migrated history row. But that file does not exist inside my project folder as i said above.

Now If I am running add-migration it is creating the whole database from scratch rather than just updating it by creating the additional tables in migration file.

Is there any way to resolve my problem ?

I tested this with a very simple DbContext. I hope this works for you.

Basically you need to create a new snapshot of your database in it's current state and use that to create an initial migration. After that you can create migrations as normal.

  1. Backup your database and Backup your project , then delete your Migrations folder if you have one.

  2. Build a temporary model and context from your database. You run this from the command line in your project folder.

dotnet ef dbcontext scaffold "{Your connection string}" Microsoft.EntityFrameworkCore.SqlServer -o TempModels -c ApplicationDbContext

Make sure -c matches the name of your existing DbContext and the provider eg. SqlServer matches your database provider.

This will create a folder named TempModels in your project and a new DbContext in the TempModels namespace.

You can read more about reverse engineering your database here https://docs.microsoft.com/en-us/ef/core/managing-schemas/scaffolding .

  1. Use this new context to create a new migration
PM> add-migration Initial -Context YourApplicationName.TempModels.ApplicationDbContext
  1. Delete the TempModels folder

  2. Manually add the file name with, out the .cs, of the migration you just created to your dbo.__EFMigrationsHistory. This is so update-database will not try to apply the migration we just made when we call it in the last step.

Example:

在此处输入图片说明

  1. In your migration .designer.cs and you ModelSnapshot files you will have to change the namespace of your DbContext
// change this
using MyApplication.TempModels

// to whatever name space your real dbcontext lives in
using MyApplication.Data

  1. Create another migration. This one will contain the differences of your original DbContext to the temporary one that you scaffolded from the database. Then use it to update your database.
PM> add-migration 1

PM> 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