Entity Framework 롤백 및 잘못된 마이그레이션 제거
수동 마이그레이션 및 업데이트와 함께 C #에서 프로젝트에 EF 6.0을 사용하고 있습니다. 데이터베이스에 약 5 개의 마이그레이션이 있지만 마지막 마이그레이션이 잘못되어 원하지 않는다는 것을 깨달았습니다. 이전 마이그레이션으로 롤백 할 수 있지만 새 (고정) 마이그레이션을 추가하고 Update-Database를 실행할 때 잘못된 마이그레이션도 적용됩니다.
이전 마이그레이션으로 롤백하려고하고 마이그레이션이 잘못된 파일을 삭제하려고했습니다. 그러나 새 마이그레이션을 추가하려고하면 마이그레이션 파일이 손상되어 데이터베이스를 업데이트 할 때 오류가 발생합니다 (특히 코드의 첫 줄은 테이블 이름을 B로 바꾸고 다음 줄은 EF가 이름 A-어쩌면 EF 버그 일 수도 있습니다).
실행할 수있는 쿼리가 있습니까? "EF에"마지막 마이그레이션은 존재하지 않았으므로 잘못되었습니다. " Remove-Migration과 같은 것.
Edit1 나에게 적합한 솔루션을 찾았습니다. 모델을 양호한 상태로 변경하고 실행 Add-Migration TheBadMigration -Force
합니다. 이것은 적용되지 않은 마지막 마이그레이션을 다시 스캐 폴드합니다.
어쨌든 이것은 여전히 원래 질문에 완전히 대답하지는 않습니다. 데이터베이스를 잘못된 마이그레이션으로 업데이트하면 나쁜 마이그레이션을 제외하고 롤백하고 새 마이그레이션을 만드는 방법을 찾지 못했습니다.
감사
두 가지 옵션이 있습니다.
잘못된 마이그레이션에서 다운을 수행하여 새 마이그레이션으로 전환 할 수 있습니다 (모델에 대한 후속 변경도 수행해야 함). 이것은 효과적으로 더 나은 버전으로 롤업하고 있습니다.
여러 환경으로 이동 한 환경에서이 옵션을 사용합니다.
다른 옵션은 실제로
Update-Database –TargetMigration: TheLastGoodMigration
배포 된 데이터베이스에 대해 실행 한 다음 솔루션에서 마이그레이션을 삭제하는 것입니다. 이것은 일종의 헐크 스매시 대안이며 나쁜 버전으로 배포 된 모든 데이터베이스에 대해 수행해야합니다.참고 : 마이그레이션을 다시 스캐 폴딩하려면을 사용할 수 있습니다
Add-Migration [existingname] -Force
. 그러나 이것은 기존 마이그레이션을 덮어 쓰므로 데이터베이스에서 기존 마이그레이션을 제거한 경우에만 수행하십시오. 기존 마이그레이션 파일을 삭제하고 실행하는 것과 동일한 작업을 수행합니다.add-migration
개발하는 동안이 옵션을 사용합니다.
질문에서 알 수 있듯이 이것은 아직 릴리스되지 않은 개발 유형 환경의 마이그레이션에 적용됩니다.
이 문제는 다음 단계로 해결할 수 있습니다. 데이터베이스를 마지막으로 올바른 마이그레이션으로 복원하고 Entity Framework 프로젝트에서 잘못된 마이그레이션을 삭제하고 새 마이그레이션을 생성하여 데이터베이스에 적용하십시오. 참고 : 주석에서 판단 할 때 EF Core를 사용하는 경우 이러한 정확한 명령을 더 이상 적용 할 수 없습니다.
1 단계 : 이전 마이그레이션으로 복원
아직 마이그레이션을 적용하지 않은 경우이 부분을 건너 뛸 수 있습니다. 데이터베이스 스키마를 이전 지점으로 복원하려면 -TargetMigration 옵션과 함께 Update-Database 명령을 실행하여 마지막으로 올바른 마이그레이션을 지정하십시오.
Update-Database –TargetMigration: <name of last good migration>
마지막으로 올바른 마이그레이션의 이름을 얻으려면 'Get-Migrations'명령을 사용하여 데이터베이스에 적용된 마이그레이션 이름 목록을 검색하십시오.
PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201508242303096_Bad_Migration
201508211842590_The_Migration_applied_before_it
201508211440252_And_another
이 목록은 가장 최근에 적용된 마이그레이션을 먼저 보여줍니다. 다운 그레이드하려는 대상 (예 : 다운 그레이드하려는 대상 이전에 적용) 후에 목록에서 발생하는 마이그레이션을 선택하십시오. 이제 Update-Database를 발행하십시오.
Update-Database –TargetMigration: "<the migration applied before it>"
지정된 마이그레이션 이후에 적용된 모든 마이그레이션은 가장 먼저 적용된 최신 마이그레이션부터 순서대로 다운 그레이드됩니다.
2 단계 : 프로젝트에서 마이그레이션 삭제
이제 EF 프로젝트 'Migrations'폴더에서 잘못된 마이그레이션을 삭제할 수 있습니다. 이제 새 마이그레이션을 작성하여 데이터베이스에 적용 할 수 있습니다.
3 단계 : 새 마이그레이션 추가
add-migration "new migration"
4 단계 : 데이터베이스에 마이그레이션 적용
update-database
ASP.NET Core v1.0.0과 함께 EF Core를 사용하는 사람들에게는 비슷한 문제가 있었고 다음 명령을 사용하여 문제를 해결했습니다 (@DavidSopko의 게시물에서 올바른 방향으로 안내했지만 EF Core의 세부 사항은 약간 다릅니다) .
Update-Database <Name of last good migration>
Remove-Migration
예를 들어, 현재 개발중인 명령은
PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM>
Remove-Migration은 마지막으로 적용한 마이그레이션을 제거합니다. 여러 마이그레이션을 제거 해야하는보다 복잡한 시나리오가있는 경우 (초기 및 불량한 2 개만 있음) 더미 프로젝트에서 단계를 테스트하는 것이 좋습니다.
현재 EF Core (v1.0.0)에 Get-Migrations 명령이없는 것 같으므로 마이그레이션 폴더를보고 수행 한 작업에 익숙해야합니다. 그러나 멋진 도움말 명령이 있습니다.
PM> get-help entityframework
Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)
Initially I tried Remove-Migration by itself and found the error command confusing:
System.InvalidOperationException: The migration '...' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.
There are already suggestions on improving this wording, but I'd like the error to say something like this:
Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will unapply all migrations that occurred after the migration specified to Update-Database. You may then run Remove-Migration (migration name to remove)
Output from the EF Core help command follows:
PM> get-help entityframework
_/\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\
TOPIC
about_EntityFrameworkCore
SHORT DESCRIPTION
Provides information about Entity Framework Core commands.
LONG DESCRIPTION
This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.
The following Entity Framework cmdlets are included.
Cmdlet Description
-------------------------- ---------------------------------------------------
Add-Migration Adds a new migration.
Remove-Migration Removes the last migration.
Scaffold-DbContext Scaffolds a DbContext and entity type classes for a specified database.
Script-Migration Generates a SQL script from migrations.
Update-Database Updates the database to a specified migration.
Use-DbContext Sets the default DbContext to use.
SEE ALSO
Add-Migration
Remove-Migration
Scaffold-DbContext
Script-Migration
Update-Database
Use-DbContext
First, Update your last perfect migration via this command :
Update-Database –TargetMigration
Example:
Update-Database -20180906131107_xxxx_xxxx
And, then delete your unused migration manually.
As of .NET Core 2.2, TargetMigration
seems to be gone:
get-help Update-Database
NAME
Update-Database
SYNOPSIS
Updates the database to a specified migration.
SYNTAX
Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]
DESCRIPTION
Updates the database to a specified migration.
RELATED LINKS
Script-Migration
about_EntityFrameworkCore
REMARKS
To see the examples, type: "get-help Update-Database -examples".
For more information, type: "get-help Update-Database -detailed".
For technical information, type: "get-help Update-Database -full".
For online help, type: "get-help Update-Database -online"
So this works for me now:
Update-Database -Migration 20180906131107_xxxx_xxxx
As well as (no -Migration
switch):
Update-Database 20180906131107_xxxx_xxxx
On an added note, you can no longer cleanly delete migration folders without putting your Model Snapshot out of sync. So if you learn this the hard way and wind up with an empty migration where you know there should be changes, you can run (no switches needed for the last migration):
Remove-migration
It will clean up the mess and put you back where you need to be, even though the last migration folder was deleted manually.
You can also use
Remove-Migration -Force
This will revert and remove the last applied migration
For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.
$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force
Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.
참고URL : https://stackoverflow.com/questions/22680446/entity-framework-rollback-and-remove-bad-migration
'IT' 카테고리의 다른 글
응용 프로그램 오류-서버 연결에 실패했습니다. (0) | 2020.06.10 |
---|---|
Matplotlib tight_layout ()은 Figure Suptitle을 고려하지 않습니다. (0) | 2020.06.10 |
"long long"= "long long int"= "long int long"= "int long long"입니까? (0) | 2020.06.10 |
오류 1044 (42000) : ''@ 'localhost'사용자가 데이터베이스 'db'에 대한 액세스가 거부되었습니다. (0) | 2020.06.10 |
SQL에서 여러 열 업데이트 (0) | 2020.06.10 |