programing tip

Entity Framework 용 데이터베이스를 다시 만드는 방법은 무엇입니까?

itbloger 2020. 6. 23. 07:54
반응형

Entity Framework 용 데이터베이스를 다시 만드는 방법은 무엇입니까?


Code-First Entity Framework를 사용하여 ASP.Net MVC 5 프로젝트에서 상태가 좋지 않습니다. 데이터 손실에 신경 쓰지 않고 새로 시작하고 데이터베이스를 다시 만들고 Code-First 마이그레이션을 사용하고 싶습니다.

현재 Update-Database를 시도 할 때마다 예외가 발생하거나 오류 메시지가 표시되는 상태입니다. 또한 웹 사이트는 데이터베이스에 올바르게 액세스 할 수 없습니다. 새 프로젝트를 만들지 않고 모든 마이그레이션을 지우고 데이터베이스를 다시 만들고 처음부터 다시 시작하려면 어떻게해야합니까? 즉, 코드를 유지하고 데이터베이스를 삭제하고 싶습니다.

나중에 배포 데이터베이스 (Azure의 SQL Server)를 동기화하고 싶습니다. 다시 한 번, 모든 데이터를 삭제하지 않아도됩니다. 데이터를 작동 시키려고합니다.

깨끗한 상태로 돌아가려면 방법 단계를 제공하십시오. 매우 감사.


아래 단계를 수행하십시오.

1) 먼저 Visual Studio의 서버 탐색기로 이동하여이 프로젝트의 ".mdf"데이터 연결이 연결되어 있는지 확인하십시오. 연결되어 있으면 마우스 오른쪽 단추를 클릭하고 삭제하십시오.

솔루션 탐색기로 이동하여 모든 파일 표시 아이콘을 클릭하십시오.

3) App_Data로 이동하여 마우스 오른쪽 버튼을 클릭하고이 프로젝트의 모든 ".mdf"파일을 삭제하십시오.

4) 마우스 오른쪽 버튼을 클릭하고 삭제하여 마이그레이션 폴더를 삭제하십시오.

5) SQL Server Management Studio로 이동하여이 프로젝트의 DB가 없는지 확인하십시오. 그렇지 않으면 삭제하십시오.

6) Visual Studio에서 패키지 관리자 콘솔로 이동하여 다음을 입력하십시오.

  1. Enable-Migrations -Force
  2. Add-Migration init
  3. Update-Database

7) 응용 프로그램을 실행

참고 : 6 단계 3 단계에서 "파일을 첨부 할 수 없습니다 ..."오류가 발생하면 SQL Server에서 데이터베이스 파일을 완전히 삭제하지 않았기 때문일 수 있습니다.


Lin의 답변이 정확하다고 덧붙이고 싶습니다.

MDF를 잘못 삭제하면 MDF를 수정해야합니다. 프로젝트의 나사 연결을 MDF에 고정합니다. 짧은 답변; 올바르게 다시 작성하고 삭제하십시오.

  1. 새 MDF를 작성하고 이전 MDF와 동일한 이름을 지정하고 동일한 폴더 위치에 두십시오. 새 프로젝트를 만들고 새 mdf를 만들 수 있습니다. mdf는 삭제하려고했기 때문에 이전 테이블과 일치하지 않아도됩니다. 따라서 오래된 폴더를 만들거나 올바른 폴더에 복사하십시오.
  2. 서버 탐색기에서여십시오 [솔루션 탐색기에서 mdf를 두 번 클릭하십시오]
  3. 서버 탐색기에서 삭제
  4. 솔루션 탐색기에서 삭제
  5. 실행 update-database -force[필요한 경우 힘을 사용하십시오]

완료, 새로운 DB를 즐기십시오

업데이트 11/12/14-나는 주요 DB 변경을 할 때 항상 이것을 사용합니다. 이것이 마이그레이션을 원본 DB로 롤백하는 좋은 방법이라는 것을 알았습니다.

  • db를 원래대로 되돌립니다.
  • 일반 마이그레이션을 실행하여 현재로 되 돌리십시오.

    1. Update-Database -TargetMigration:0 -force [이로 인해 모든 테이블과 모든 데이터가 삭제됩니다.]
    2. Update-Database -force [필요한 경우 사용 힘]

이것은 나를 위해 일했다 :

  1. Visual Studio의 SQL Server 개체 탐색기에서 데이터베이스를 삭제하십시오. 마우스 오른쪽 버튼을 클릭하고 삭제를 선택하십시오.
  2. 파일 시스템에서 mdf 및 ldf 파일을 삭제하십시오 (아직있는 경우).
  3. 솔루션을 다시 빌드하십시오.
  4. 응용 프로그램 시작-데이터베이스가 다시 작성됩니다.

이 질문은 데이터를 신경 쓰지 않음으로써 전제되지만 때로는 데이터 유지 관리가 필수적입니다.

그렇다면 데이터베이스에 이미 같은 이름의 테이블이있을 때 Entity Framework 악몽에서 복구하는 방법에 대한 단계 목록을 작성했습니다. Entity Framework 악몽 에서 복구하는 방법-데이터베이스에 이미 같은 이름의 테이블이 있습니다.

분명히 ... 중재자가 게시물을 삭제하기에 적합하므로 여기에 붙여 넣을 것입니다.

Entity Framework 악몽에서 복구하는 방법-데이터베이스에 이미 동일한 이름의 테이블이 있습니다.

설명 : 팀이 EF를 처음 접했을 때 우리와 같다면 새 로컬 데이터베이스를 만들 수 없거나 프로덕션 데이터베이스에 업데이트를 적용 할 수없는 상태가됩니다. 깨끗한 EF 환경으로 돌아간 다음 기본 사항을 고수하고 싶지만 할 수는 없습니다. 프로덕션 환경에서 작동하게되면 로컬 DB를 만들 수 없으며 로컬 환경에서 작동하면 프로덕션 서버가 동기화되지 않습니다. 마지막으로 프로덕션 서버 데이터를 삭제하고 싶지 않습니다.

증상 : 생성 스크립트를 실행하려고하는데 데이터베이스에 이미 같은 이름의 테이블이 있으므로 Update-Database를 실행할 수 없습니다 .

오류 메시지 : System.Data.SqlClient.SqlException (0x80131904) : 데이터베이스에 ''라는 이름의 개체가 이미 있습니다.

문제 배경 : EF는 dbo .__ MigrationHistory라는 데이터베이스의 테이블을 기반으로 코드가있는 위치와 현재 데이터베이스의 위치를 ​​이해합니다. 마이그레이션 스크립트를 볼 때 스크립트와 함께 마지막 위치를 재조정하려고합니다. 그것이 가능하지 않다면, 순서대로 적용하려고 시도합니다. 즉, 초기 작성 스크립트로 돌아가서 UP 명령의 첫 번째 부분을 보면 오류가 발생한 테이블의 CreeateTable이됩니다.

이것을 더 자세히 이해하려면 여기에 언급 된 두 비디오를 모두 보는 것이 좋습니다. https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx

솔루션 : 우리가해야 할 일은 이러한 CreateTable 명령을 적용하지 않고 현재 데이터베이스가 최신 상태라고 생각하도록 EF를 속이는 것입니다. 동시에, 우리는 여전히 새로운 로컬 데이터베이스를 생성 할 수 있도록 이러한 명령이 존재하기를 원합니다.

1 단계 : 프로덕션 DB 정리 먼저 프로덕션 DB를 백업합니다. SSMS에서 데이터베이스를 마우스 오른쪽 단추로 클릭하고 "작업> 데이터 계층 응용 프로그램 내보내기 ..."를 선택하고 지시를 따릅니다. 프로덕션 데이터베이스를 열고 dbo .__ MigrationHistory 테이블을 삭제 / 삭제하십시오.

2 단계 : 로컬 환경 정리 마이그레이션 폴더를 열고 삭제합니다. 필요한 경우 git 에서이 모든 것을 다시 얻을 수 있다고 가정합니다.

Step 3: Recreate Initial In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts). Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code. If you had any seed operations in the previous Configuration.cs, then copy that across.

Step 4: Trick EF At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.

Step 5: Update-Database With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like. Now, uncomment that code and save. You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.

Step 6: Confirm EF is ACTUALLY up to date If you had code that hadn't yet had migrations applied to it, this is what I did...

Run "Add-Migration MissingMigrations" This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.

Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.

Step 7: Re-confirm and commit. Build, test, run. Ensure that everything is running then commit the changes.

Step 8: Let the rest of your team know how to proceed. When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.


Just want to add to the excellent answer of @Lin:

5) B. If you don't have SQL Management Studio, go to "SQL Server Object Explorer". If you cannot see your project db in the localdb "SQL Server Object Explorer", then click on "Add SQL server" button to add it to the list manually. Then you can delete the db from the list.


A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.


My solution is best suited for :
- deleted your mdf file
- want to re-create your db.

In order to recreate your database you need add the connection using Visual Studio.

Step 1 : Go to Server Explorer add new connection( or look for a add db icon).

Step 2 : Change Datasource to Microsoft SQL Server Database File.

Step 3 : add any database name you desire in the Database file name field.(preferably the same name you have in the web.config AttachDbFilename attribute)

Step 4 : click browse and navigate to where you will like it to be located.

Step 5 : in the package manager console run command update-database

참고URL : https://stackoverflow.com/questions/20304058/how-to-re-create-database-for-entity-framework

반응형