ASP.NET MVC4 Code First - 'Cannot attach the file as database' exception

后端 未结 4 889
独厮守ぢ
独厮守ぢ 2020-12-21 03:58

I\'m using Code First concept in Entity Framework and I\'m constantly getting the following exception while starting application:

Cannot attach the file \'C:         


        
相关标签:
4条回答
  • 2020-12-21 04:15

    I found the solution. With newest SQL Server Management studio there is no problem in connecting to the local database. Connection needs to be established like this:

    enter image description here

    After logging in we can still see old database present even if there is nothing under App_Data directory and under Data Connections in Server Explorer in Visual Studio. When we delete that database from SQL Server Management studio and start application again there will be no more errors while attaching database.

    0 讨论(0)
  • 2020-12-21 04:25

    I just got into the same problem, and yet the answers above helped, the solution was different.

    In my case, I was reusing a project that has already created it´s database. And since the name in the config was the same, it was throwing the exception, missleading the real solution.

    It worth checking the database is not created and is different than the ones you used before. Change the name and go ahead.

    0 讨论(0)
  • I deleted the mdf file manually so the code will recreate it again, and had the same problem. I solved it by running update-database command in the package manager console.

    0 讨论(0)
  • 2020-12-21 04:28

    I was facing the same error when I saw this but I couldn't delete the database using SQL Server Management Studio so I remembered IDatabaseInitializer.

    Setting a database initializer for my Code First context solved the issue. In my case adding an initializer to always drop the DB worked (I added the code in the static constructor of my context, most people add it in Global.asax):

        static SomeDbContext()
        {
            System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseAlways<SomeDbContext>());
        }
    

    There are other initializers of course.

    0 讨论(0)
提交回复
热议问题