Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot attach the file ".mdf" as database "aspnet-"

I'm using web sockets and SqlDependency to build a game server. An error with the SqlDataReader indicated that I should call SqlDependency.Start. I included the following in my Global.Asax:

SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

This line always ends with the SqlException, with message:

Cannot attach the file 'C:...aspnet-ProjectName-11111111111.mdf' as database 'aspen-ProjectName-11111111111'.

I've been trying to fix this for two days. I've started a fresh MVC 4 WebAPI app, with a basic model, context, and seed, and can't get around this error. I've tried the various solutions in the following:

https://social.msdn.microsoft.com/Forums/en-US/ae041d05-71ef-4ffb-9420-45cbe5c07fc5/ef5-cannot-attach-the-file-0-as-database-1?forum=adodotnetentityframework

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

EF5: Cannot attach the file ‘{0}' as database '{1}'

No change. I'm running MVC4 API in Visual Studio 2012, SQL Server is 2014.

This is a DB connection problem, right? The .mdf file in my AppData folder (both it and the log file are there in both projects) can't be connected to SQL Server? Also, help?

like image 777
dylanthelion Avatar asked Oct 24 '25 13:10

dylanthelion


2 Answers

I encountered the same problem as you.

In your Web.config file, find you connection string, copy and paste it and then remove everything after the 'MultipleActiveResultSets' - apart from the providerName.

So in mine, it changed from this:

<add name="ApplicationName" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|ApplicationNameContext-20151023111236.mdf" providerName="System.Data.SqlClient" />

Became this:

<add name="NotificationConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True;" providerName="System.Data.SqlClient" />

And as you will notice the connection has a different name. The connections will still query the same database.

Now modify your connection string name in the Dependency.Start parameter to be your the name of the connection string you just created:

SqlDependency.Start(ConfigurationManager.ConnectionStrings["NEW_CONNECTION_NAME"].ConnectionString);
like image 78
MalvEarp Avatar answered Oct 27 '25 04:10

MalvEarp


Remove the Initial Catalog property in your connection string.

You should see this answer: https://stackoverflow.com/a/20176660/161471

like image 44
Thach Lockevn Avatar answered Oct 27 '25 03:10

Thach Lockevn