Nice programing

* .mdf 파일을 데이터베이스로 연결할 수 없습니다.

nicepro 2020. 11. 12. 20:12
반응형

* .mdf 파일을 데이터베이스로 연결할 수 없습니다.


기본적으로 나는 튜토리얼을 따랐고 .mdf나중에 파일 을 삭제하기로 결정 했습니다.

이제 응용 프로그램을 실행하려고 할 때마다 다음 오류 (이 스레드의 제목)가 표시됩니다. 오류가 발생한 코드는 다음과 같습니다 (ASP.NET MVC 4).

OdeToFoodDB db = new OdeToFoodDB();

public ActionResult Index()
{
    var model = db.Restaurants.ToList();
    return View(model);
}

내 연결 문자열은 다음과 같습니다.

<add name="DefaultConnection" 
     connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=OdeToFoodDb;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OdeToFoodDb.mdf" 
     providerName="System.Data.SqlClient" />

SQL Server 개체 탐색기를 살펴 보았지만 다음과 같이 보입니다.

또한 서버 탐색기에서 데이터 연결이 표시되지 않습니다.

서버 탐색기에서 새 연결을 추가하려고 할 때라는 데이터베이스가 표시되지 않습니다 OdeToFoodDb.

이 광범위한 질문에 대해 죄송하지만 Entity Framework를 처음 사용하고 여기서 무엇이 잘못되었는지 이해하지 못합니다.


이것을보세요 : Entity Framework는 데이터베이스를 만들지 않습니다.

데이터베이스에 다른 이름을 지정하려고합니다. 두 번째로 동일한 이름으로 데이터베이스를 만들려고 할 때 SQL Express에 문제가 발생할 수 있습니다. SQL Server Management Studio를 사용하여이 문제를 해결하는 방법이 있지만 일반적으로 다른 데이터베이스 이름을 사용하는 것이 더 쉽습니다.

편집 이 답변은 OP에서 사용 하는 버그 및 해결 방법을 확인하기 때문에 수락되었습니다 (데이터베이스 이름 변경이 도움이수 있음 ). 나는 데이터베이스 이름을 바꾸는 것이 실제로 허용되는 방법 이 아니며 문제를 완전히 해결하지 못한다 는 데 전적으로 동의합니다 . 안타깝게도 SSMS에서 실제로 해결하는 다른 방법은 확인하지 않았습니다.


SQL Server Local Db의 경우 Initial Catalog속성을 사용하면 안된다고 생각합니다 . 다음을 사용하는 것이 좋습니다.

<add name="DefaultConnection" 
     connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OdeToFoodDb.mdf" 
     providerName="System.Data.SqlClient" />

로컬 db가 동일한 mdf 파일에서 여러 데이터베이스를 지원하지 않는다고 생각하므로 초기 카탈로그가 지원되지 않거나 잘 지원되지 않으며 이상한 오류가 있습니다.


  1. 패키지 관리자 콘솔에서 다음을 실행하십시오.

    sqllocaldb.exe stop v11.0

    sqllocaldb.exe delete v11.0

  2. 프로젝트 실행

  3. 사용자 등록

해야 할 연결 문자열에서이 줄을 제거하십시오.;) "AttachDbFilename = | DataDirectory | whateverurdatabasenameis-xxxxxxxxxx.mdf"


" 'C : \ Github \ TestService \ TestService \ App_data \ TestService.mdf"파일을'TestService '데이터베이스로 첨부 할 수 없습니다.

위의 오류 메시지가 나타나면 다음 단계를 수행하십시오.

  1. SQL Server 개체 탐색기 열기
  2. 새로 고침 버튼을 클릭합니다.
  3. (localdb) \ MSSQLLocalDB (SQL Server 12.x.xxxxx-xxxxx \ xxxx)를 확장합니다.
  4. 데이터베이스 확장
  5. 존재하는 동일한 이름 데이터베이스를 제거하십시오.
  6. 오른쪽 버튼 클릭 후 삭제
  7. 패키지 관리 콘솔로 돌아 가기
  8. 데이터베이스 갱신

나는 같은 문제에 직면했습니다. VS 2013의 다음 단계로 문제가 해결되었습니다.

  1. 서버 탐색기에서 새 데이터베이스에 연결 추가
  2. Microsoft SQL Server 데이터베이스 파일을 데이터 소스로 선택
  3. web.config의 연결 문자열에 따라 있어야하는 데이터베이스 파일 이름을 선택합니다.
  4. 새 데이터베이스 파일이 생성되고 서버 탐색기에 "MyDatabaseName"및 "MyDatabaseName (MyProjectName)"이라는 두 개의 데이터베이스 연결이 나타납니다.
  5. 하나의 연결 삭제 ( "MyDatabaseName"을 삭제했습니다)

서버 탐색기에 해당 데이터베이스의 이전 복사본이 이미 설치되어 있습니다. 따라서 서버 개체 탐색기 / SQL 서버에서 간단한 명명 충돌이 발생합니다. Apps_Data 폴더로 이동하기 전에 이미 동일한 데이터베이스 카탈로그 이름을 만들었을 수 있습니다. 따라서 데이터베이스 이름이 이미 존재하고 삭제하기 만하면됩니다.

Visual Studio>보기> SQL Server 개체 탐색기로 이동하여 이전 데이터베이스 이름과 해당 연결을 삭제하면됩니다. 앱을 다시 시도하면 App_Data에 .mdf 파일을 설치하고 서버 탐색기에서 동일한 정확한 데이터베이스를 다시 만들어야합니다.


@ davide-icardi에 따라 "Initial Catalog = xxx;"를 제거하십시오. web.config에서 삭제하고 여기에서도 azure 게시 프로필 파일을 확인하여 제거합니다.
[YourAspNetProject path] \ Properties \ PublishProfiles [YourAspNetProjectName] .pubxml

<PublishDatabaseSettings>
  <Objects xmlns="">
    <ObjectGroup Name="YourAspNetProjectName" Order="1" Enabled="True">
      <Destination Path="Data Source=AzureDataBaseServer;Initial Catalog=azureDatabase_db;User ID=AzureUser_db_sa@AzureDataBaseServer;Password=test" />
      <Object Type="DbCodeFirst">
        <Source Path="DBMigration" DbContext="YourAspNetProjectName.Models.ApplicationDbContext, YourAspNetProjectName" MigrationConfiguration="YourAspNetProjectName.Migrations.Configuration, YourAspNetProjectName" Origin="Configuration" />
      </Object>
    </ObjectGroup>
  </Objects>
</PublishDatabaseSettings>

SQL SERVER Management Studio를 사용하여이 문제를 해결하려면

문제 : 'YourConnStringNamedContext'데이터베이스로 'YourDB.mdf'파일을 첨부 할 수 없습니다.와 같은 오류가 발생합니다.

Reason: happens because you deleted the backing files .mdf, ldf without actually deleting the database within the running instance of SqlLocalDb; re-running the code in VS won't help because you cannot re-create a DB with the same name (and that's why renaming works, but leaves the old phantom db name lying around).

The Fix: I am using VS2012, adopt similarly for a different version.

Navigate to below path and enter

c:\program files\microsoft sql server\110\Tools\Binn>sqllocaldb info

Above cmd shows the instance names, including 'v11.0'

If the instance is already running, enter at the prompt

sqllocaldb info v11.0

Note the following info Owner: YourPCName\Username , State: Running , Instance pipe name: np:\.\pipe\LOCALDB#12345678\tsql\query , where 123456789 is some random alphanumeric

If State is not running or stopped, start the instance with

sqllocaldb start v11.0

and extract same info as above.

In the SS Management Studio 'Connect' dialog box enter

server name: np:\.\pipe\LOCALDB#12345678\tsql\query

auth: Windows auth

user name: (same as Owner, it is grayed out for Win. auth.)

Once connected, find the phantom DB which you deleted (e.g. YourDB.mdf should have created a db named YourDB), and really delete it.

Done! Once it's gone, VS EF should have no problem re-creating it.


I found that commenting out the context section used to initialise the database resolved the problem. Havnt had time to find out what was wrong with the seeding statements yet, but removing the seeding resolved the problem.


I had the same error while following the tutorial on "Getting Started with ASP.NET MVC 5 | Microsoft Docs". I was on Visual Studio 2015. I opened View-> SQL Server Object Explorer and deleted the database named after the tutorial, then it could work. see Delete .mdf file from app_data causes exception cannot attach the file as database


Ran into this issue. Caused in my case by deleting the .mdf while iispexress was still running and therefor still using the DB. Right click on iisexpress in system tray and click exit THEN delete the MDF to prevent this error from actually occurring.

To fix this error simply within VS right click the App-Data folder add new item > SQL Server Database. Name: [use the database name provided by the update-database error] Click Add.


Just change database name from web.config project level file and then update database.

connectionString = Data Source =(LocalDb)\MSSQLLocalDB;AttachDbFilename="|DataDirectory|\aspnet-Project name-20180413070506.mdf";Initial Catalog="aspnet--20180413070506";Integrated

Change the bold digit to some other number:

connectionString = Data Source==(LocalDb)\MSSQLLocalDB;AttachDbFilename="|DataDirectory|\aspnet-Project name-20180413070507.mdf";Initial Catalog="aspnet--20180413070507";Integrated


Recreate your database. Do not delete it and your app should continue to work.


I had the same error. Weird thing was, I had one new project form scratch, there it worked perfectly and another, much bigger project, where I always ran into that error message.

The perfecrtly working project (nearly) always creates the database (indluding the files) automatically. It can be any command, read, write, update. The files get created. Of course it uses

DropCreateDatabaseIfModelChanges

There is only one case, when it gets troubled: IF the mdf is auto-created and you delete the mdf and log file. Then that was about it. Say good-bye to your autocreation...

The only way I found to fix it was like mentioned:

sqllocaldb stop v11.0 & sqllocaldb delete v11.0

After that, everything is back to normal (and all other Databases handled by LocalDB also gone!).

EDIT: That was not true. I just tried it and the v11.0 gets automatically recreated and all mdfs stay available. I have not tried with "non file based" LocalDBs.

The confusing thing is, I also got this error if something else was wrong. So my suggestion is, if you want to make sure your DB-Setup is sound and solid: Create a new solution/project from scratch, use the most basic DB commands (Add an entity, show all entities, delete all entities) and see if it works.

If YES, the problem is somewhere in the abyss of VS2013 config and versioning and nuget and stuff.

IF NO, you have a problem with your LocalDB installation.

For anyone who really wants to understand what's going on in EF (and I am still not sure if I do :-) ) http://odetocode.com/Blogs/scott/archive/2012/08/14/a-troubleshooting-guide-for-entity-framework-connections-amp-migrations.aspx

P.S.: Nudge me if you need the running example project.


Strangely, for the exact same issue, what helped me was changing the ' to 'v11.0' in the following section of the config.

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>

I recently ran into the same problem. Here is one thing to check. in visual studio there are three place we should check and remove the database.

1. Solution Explorer's App_Data folder
2. Server Explorer's Data Connection menu
3. SQL Server Object Explorer

When I delete database from the first two point, the error still occurs. So, I needed to delete the database from the SQL Server Object Explorer as well. Then I could easily run the 'update-database' command without error. Hope this helps.


We just ran into this ourselves when running dotnet ef database update using ASP.Net Core 2.1; looks like relative paths aren't supported with AttachDbFileName.

System.Data.SqlClient.SqlException (0x80131904): Cannot attach the file '.\OurDbName.mdf' as database 'OurDbName'.

Just wanted to express that here for other people who might be bumping into this. The "fix" is use absolute paths.

See also: https://github.com/aspnet/EntityFrameworkCore/pull/6446


If you happen to apply migrations already this may fix it.

Go to your Web.config and update your connection string based on your migration files.

Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-GigHub-201802102244201.mdf;Initial Catalog=aspnet-GigHub-201802102244201;

The datestrings should match the first numbers on your Migrations.


Ran into the similar problem not exactly the same, A case of Database already existed the issue was solved by following code.

<add name="DefaultConnection" connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\aspnet-EjournalParsing-20180925054839.mdf;Initial Catalog=aspnet-EjournalParsing-20180925054839;Integrated Security=True"
      providerName="System.Data.SqlClient" />

참고URL : https://stackoverflow.com/questions/17012839/cannot-attach-the-file-mdf-as-database

반응형