尝试附加文件[..]的自动命名数据库失败.存在具有相同名称的数据库[..]



使用LocalDB开发实体框架项目会在。。。

  • 使用class Initializer : DropCreateDatabaseIfModelChanges<Context>和实体框架6.4
  • 用实体框架核心3.1调用Database.EnsureDeleted(); Database.EnsureCreated();

错误消息

An attempt to attach an auto-named database for file D:DocumentsVisual Studio-ProjekteEF-TestbinDebugnetcoreapp3.1EF-DB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

连接

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


发生此异常的原因是什么?

清除解决方案时会发生这种情况。

清除解决方案时,.mdf/.ldf文件将与bin目录一起被删除,但SQL Server Express LocalDB的master数据库将保留对(已删除但现在丢失的(数据库文件的引用。

显然,无论是实体框架6.4中的数据库初始化程序,还是实体框架核心3.1中的数据库创建者,都不会在不抛出上述错误消息的情况下处理这种情况。

最新更新