Using LocalDB for developing an Entity Framework project yields the following error when ...

  • using class Initializer : DropCreateDatabaseIfModelChanges<Context> with Entity Framework 6.4
  • calling Database.EnsureDeleted(); Database.EnsureCreated(); with Entity Framework Core 3.1

The error message

An attempt to attach an auto-named database for file D:\Documents\Visual Studio-Projekte\EF-Test\bin\Debug\netcoreapp3.1\EF-DB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

The Connection

Context db = new Context(@"Server=(LocalDB)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName="
                        + Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                          "EF-DB.mdf"))


What is the cause for this exception to happen?

1

There are 1 best solutions below

0
On

This happens when you clear your solution.

When you clear your solution, the .mdf/.ldf files get deleted along with the \bin\ directory, yet SQL Server Express LocalDB's master database keeps a reference to the (deleted and now missing) database files.

Apparently, neither database initializers in Entity Framework 6.4 nor the database creator in Entity Framework Core 3.1 handle this situation without throwing above error message.