Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104841

ASP.NET Core: An attempt to attach an auto-named database for file failed

I know this question has been asked many times, but I'm still unable to find a question similar to my scenario.

I'm working on an ASP.NET Core WebAPI project. It all worked well and I can't really reproduce what if at all I did to screw this up.

It's supposed to debug using this connection string, which is retrieved from the appsettings.Development.json file:

"DefaultConnection":
  "Data Source=(localdb)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|MyProj.mdf"

When calling context.Database.CreateIfNotExists();, I get the following error:

System.Data.SqlClient.SqlException occurred (HResult 0x80131904):

An attempt to attach an auto-named database for file C:\Users\Shimmy\Documents\Visual Studio 2017\Projects\MyProj\MyProj.Api\AppData\MyProj.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Source: .Net SqlClient Data Provider
StackTrace: at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

I'm running the WebAPI as a Kestrel console app.

Here's what I've tried:

Replacing the AttachDbFilename flag with Initial Catalog=MyProj, raised this error:

System.Data.SqlClient.SqlException occurred
HResult: 0x80131904
Message: Cannot open database "MyProj" requested by the login. The login failed. Login failed for user 'SHIMMY-PC\Shimmy'.
Source: .Net SqlClient Data Provider
StackTrace: at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

But SHIMMY-PC\Shimmy does appear to be in the instance's users:

enter image description here

Upvotes: 3

Views: 2144

Answers (2)

Stefan
Stefan

Reputation: 17698

In the .net core environment, you should be able to fix it by bypassing the auto-naming part. Just add :

Initial Catalog=MyNotAutoNamedDb;

somewhere in the connection string and it should work.

[note: do not replace AttachDbFilename!]

Upvotes: 1

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104841

I got it to work only if I pre-create the database file, which isn't really what I want but I'm not gonna fight over it.

BTW, I found a convenient way to drop/create database that doesn't cause so much trouble. I open the developer CLI and navigate to the project/solution folder, then call dotnet ef database, first with drop then update.

Upvotes: 0

Related Questions