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

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:\Users\Admin\Documents\Visual Studio 2012\
Projects\Pro\Pro.Web\App_Data\Pro.mdf' as database 'Pro'.
I've put this in Global.asax.cs but also without success:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ProWebContext>());
var ctx = new ProWebContext();
ctx.Database.Initialize(true);
I've checked under App_Data directory and there no database created. Also, under Server Explorer there is nothing under Data Connections. Everything was working fine yesterday and today not working at all. I've tried to connect to LocalDB with SQL Server Management studio but it says it cannot connect to local database. Any ideas what could be a problem?
Thanks!

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:
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.

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.

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.

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.

Related

Login and account registration broken on MVC application

Hello I'm new to MVC and have been looking for a solution to my problem for the last couple days with no avail.
I've created a simple blog engine using ASP.NET MVC, after installing it on IIS on my local PC, I quickly realized I needed a database for the login service to work.
So I elected to use LocalDB on a PC that I plan to use as a server. I moved my files over to the PC and installed everything I needed. As soon as I installed SQLExpress with LocalDB and reset the site, everything was working perfectly. However, I noticed some minor typos on a section of the site that's not easily edited. Stupidly, I reinstalled the website entirely from a new build instead of just updating the view that needed correction like a smart person would do.
Now every time I attempt to login to an excising account or create a new one I simply get the error
Cannot attach the file 'C:\inetpub\wwwroot\App_Data\aspnet-FacetBlog-20161020065352.mdf' as database 'aspnet-FacetBlog-20161020065352'.
From what I've learned, It's something to do with my LocalDB instance, but fixes I've found online seem to have no effect.
Admittingly, I'm pretty naive with it comes to SQL, so hopefully the fix is simple. If I've failed to provide vital information please tell me and I'll update the question. Additionally, an explanation of what exactly went wrong would be much appreciated. Thank you for your time.
When reinstalling your site, probably you had deleted database file aspnet-FacetBlog-20161020065352.mdf in your database directory. Since deleting MDF file doesn't affect registered SQL Express instance, SQL Express thinks the database still exists and trying to connect but failed.
First, try to attach the DB using SSMS query like this:
EXEC sp_attach_db #dbname=N'aspnet-FacetBlog-20161020065352.mdf', #filename1=N'App_Data\aspnet-FacetBlog-20161020065352.mdf', #filename2=N'App_Data\aspnet-FacetBlog-20161020065352.ldf'
NB: I assumed your MDF file location stands in App_Data directory, change it to your actual database directory.
If attempt to attach by query doesn't work, try these steps:
Stop IIS/IIS Express pool if it still running.
Open a Windows Powershell instance on your server PC (install it first if doesn't exist).
Run the following command:
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
sqllocaldb.exe start v11.0
Recreate the DB instance on your project, including data connection in Server Explorer (remove then create).
Re-run the project in development machine, then copy all required files to server PC. The database instance should be (re-)generated at this time.
Restart IIS/IIS Express pool on server PC.
Additionally you may run Update-Database command from Package Manager Console to ensure database integrity.
If those solutions still won't work altogether, simply rename your database files and attach it on your project, verify the connection string then retry step (5) and (6) above.
Related problems:
EF5: Cannot attach the file ‘{0}' as database '{1}'
Cannot attach the file ".mdf" as database "aspnet-"
Delete .mdf file from app_data causes exception cannot attach the file as database
Cannot attach the file 'C:\inetpub\wwwroot\MvcApplication10\App_Data\aspnet-MvcApplication10-20130909002323.mdf' as database 'aspnet-MvcApplication10-20130909002323'

How to work with LocalDB and EF, without using migrations

I am on VS 2012 RTM, with EF 5. I am doing Code First, but trying to ignore Code Migrations since I am just in development. To avoid them, I have this set
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());
Occasionally, even when I don't think I've touched the model, it decides to recreate. That's fine. But it usually results in the error
Cannot drop database because it is currently in use.
So I decided to delete the database entirely. I go into VS, go to the "SQL Server Object Explorer", find the DB and delete it. Now I'm stuck at
Cannot attach the file '{0}' as database '{1}'
I had this happen last night and I just fiddled around until it work (shut down tasks, restart VS, changed the DB and file names in the web.config, etc.
So question 1) How do I get out of this state?
But the more important question, how do I prevent myself from getting in this state at all?
The SQL Server Object Explorer window can hold a connection to the database. Closing the window and all windows opened from it releases the connection.
I had the same problem and managed to fix it. The main problem is that EF won't automatically create the database. The solution is not very hard.
First, go to the Solution Explorer and manually create the database. To do this, go to the folder where your database is located (usually App_Data). Right-click on this folder and click on Add -> New Item. Select the Data tab and select SQL Server Database. Make sure you enter the name Entity Framework expects (which is specified in the Cannot attach the file '{0}' as database '{1}' error message).
Then most likely you will get an error message that says that the database does not contain any model metadata. To circumvent this, change your database initialisation to:
Database.SetInitializer(new DropCreateDatabaseAlways<SomeContext>());
Now run the application and the database should be there with tables correctly created. Once this step has been successfully executed, you change change your database initializer back to:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());

Creating Membership DB (ASPNETDB) on remote server?

I'm building a web application which soon I'll be promoting to production. This application has a login screen, as you know I used the integrated DB for developing. Now I want to move this database to a full SQL Server 2005. I'm using the aspnet_regsql.exe to create my membership tables and stored procedures in the SQL Server 2005 but I'm getting an error:
An error occurred during the execution of the SQL file 'InstallMembership.sql'. The SQL error number is 207 and the SqlException message is: Invalid column name 'FailedPasswordAnswerAttemptWindowStart'.
I google this for half of the day already and I can't seem to fine what's wrong, does anybody have ANY ideas on what am I doing wrong here? Any help will be really appreciate it.
The easiest way to deploy a brand new database to a remote server is to just publish the database from within Visual Studio. Once you do that you have the scheme and data all in one script. You then access your server either via a local SQL manager connection or a remote manager and run the script on your remote database.
The site 4GuysFromRolla has a nice little walk through with graphics which describe how to accomplish the publishing of your local database to your hosted one.
Good luck, and hope this helps you out some.
Go through the *.sql script file and see where that column reference is. Then you'll be able to see what exactly the script is doing to cause this error. My guess would be that it is getting caught up on referential integrity. If it is trying to create a foreign key constraint that that table/column does not exist then you'll see that error.
But back to the original question at hand. You don't need to recreate your whole database. That script file is to lay down the Membership for an empty database. If you have a working dev database you can just back it up and restore it to a production instance. No need to rebuild the membership database objects.

Unable to connect to SQL database in AppData when deployed to web server

I have a ASP.Net program written in C# that uses a database stored in the AppData directory, the program works perfectly on my development (Win7\SQL 2008R2) when I deploy to a Win2008R2\SQl 2008 R2 server the program is unable to connect to the database. I'm using the connection string below. Several sites suggest I set the Application Pool to use 'Network Service' as this has Modify permission to the AppData directory, I have done this but it still won't work, another site suggested I Application Pool to "Load User Profile = True" but still no joy.
I'm pulling my hair out with what else to try, can anyone help?
data source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\DB.mdf;User
Instance=true
I get "Object reference not set to an instance of an object." in my app and "An attempt to attach an auto-named database for file C:\inetpub\wwwroot\ADPhonebook\App_Data\DB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share." in the Application Event Log
I really appreciate any advice, thanks.
Steven
As Martin points out in the comments, it would be interesting if you posted the exact error message (and maybe the full exception detail) you are getting.
But problems like this have mostly to do with rights at the OS level.
So make sure that the user (identity) of the Application Pool has full access (ntfs) rights to the .mdf file, and try again.
Edit (after you posted the exact message):
Ok, I guess this means that on the server you're deploying to, there is already a database called DB on that Sql Server instance. So you will have to remove or rename that one in order to be able to attach a database with that name.
I think the user rights problem is also still possible though.

SQL Express & IIS - A database won't attach if you manually detached it?

Since the answers did not really cover the problem, I posted this on ASP.Net and completly rephrased it. I will post the edited question here:
I have been using the attachDB connection string and I usually deploy to IIS. The site works fine, however, I made some changes to the database and the newest version would not copy as it said file in use.
I opened up SQL management studio and saw that it was mounted so I did a dettach.
I was then able to copy the new version without problem, however, when I next run the site, I get:
Unable to open the physical file "C:\inetpub\wwwroot\vs\App_Data\aspnetdb.mdf". Operating system error 5: "5(failed to retrieve text for this error. Reason: 15105)".
An attempt to attach an auto-named database for file C:\inetpub\wwwroot\vs\App_Data\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
And, if I try to access .Net users or the other few options within IIS Manager, I get the following error:
.NET Users
There was an error while performing this operation.
Details:
A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
OK
I have tried recycling the application pool, restarting the SQL instance and even restarting the computer.
Nothing helps and I cannot figure out what is wrong... Where does it remember where previous databases are connected and why doesn't it automatically reattach the database?... Someone said that they auto detach after 2 1/2 hours, however I waited 5 hours when a database wasn't in use and SQL Manager showed it was still attached.
When I manually reattach the database, everything works fine.
When you ask a database to be attached on-the-fly to a SQL Express instance using the AttachDBFileName connections string the application will not connect to the SQL Expres sinstance at all, but instead it will connect to a child instance, which is an new instance created specificaly for the user requesting the attach operation. See SQL Server 2005 Express Edition User Instances. This child instance will attach the database and will continue to run for up two one hour, after which it will shut itself down.
When you try to connect from 'enterprise manager' you will not be able to connect to the child instance (is realy complicated to connect explicitly to one, so you cannot accidentaly do it), you are connecting to the parent instance and messing with the database.
To summarize, either stick with the RANU model and use AttachDBFileName, or use a normal database operations mode and manage the database from the SSMS. Don't mix the two.
Are you certain there isn't already a database with the same name attached to the SQL Express instance you are pointing your site at?
Also, does the identity the site is running under when it attempts to attach the database have admin rights in SQL Express? If not, this command won't work (I'm not sure what error it gives in that situation, but "Access Denied" would sound reasonable).
The page "SQL Server 2005 Express Edition User Instances" seems to give a good overview of the issues and workarounds.
Edit to add
Could this be the issue:
An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.
Taken from the documentation for SqlConnectionStringBuilder.AttachDBFileName Property
You'll need to delete the log file before you can re-attach the database through this method.

Resources