简体   繁体   English

“数据库已经存在。 选择一个不同的数据库名称。 恢复C#Win App数据库后,无法附加文件…”错误

[英]“Database already exists. Choose a different database name. Cannot attach the file…” error after restoring database of c# win app

I develop a C# win Application that uses a database "OlgooDB.mdf". 我开发了一个使用数据库“ OlgooDB.mdf”的C#win应用程序。

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Database.SetInitializer(new MigrateDatabaseToLatestVersion<OlgooContext, Configuration>());

Application--> Migration --> Configuration: 应用程序->迁移->配置:

internal sealed class Configuration : DbMigrationsConfiguration<App.Model.OlgooContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
        ContextKey = "App.Model.OlgooContext";

        string dataDirPath = Application.StartupPath + "\\Database";
        AppDomain.CurrentDomain.SetData("DataDirectory", dataDirPath);
    }

    protected override void Seed(App.Model.OlgooContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

When the connection String is defined as: 当连接字符串定义为:

<connectionStrings>
<clear/>
<add name="OlgooContext" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog = OlgooDB; Integrated Security=True; " providerName="System.Data.SqlClient"/> </connectionStrings>

I can restore the database without any problem but when i changed the connection String to: 我可以毫无问题地还原数据库,但是当我将连接字符串更改为:

 <connectionStrings>
<clear/>
<add name="OlgooContext" connectionString="Data Source =.\SQLExpress;AttachDbFilename=|DataDirectory|\OlgooDB.mdf; Database=OlgooDB; Integrated Security=True;" providerName="System.Data.SqlClient"/> </connectionStrings>

This error occurred after restoring: 恢复后发生此错误:

system.data.sqlclient.sqlexception(0x80131904): database 'c:\\program files\\microsoft sql server\\mssql10.sqlexpress\\mssql\\data\\OlgooDB.mdf' already exist. system.data.sqlclient.sqlexception(0x80131904):数据库'c:\\ program files \\ microsoft sql server \\ mssql10.sqlexpress \\ mssql \\ data \\ OlgooDB.mdf'已经存在。 choose a different database name. 选择一个不同的数据库名称。 Cannot attach the file 'D:...\\bin\\Debug\\Database\\OlgooDB.mdf' as database 'OlgooDB'... 无法将文件'D:... \\ bin \\ Debug \\ Database \\ OlgooDB.mdf'作为数据库'OlgooDB'附加...

Restore Function: 恢复功能:

private void backgroundWorkerRestore_DoWork(object sender, DoWorkEventArgs e)
    {
        using (var context = new OlgooContext())
        {
            string command = "ALTER DATABASE OlgooDB SET OFFLINE WITH ROLLBACK IMMEDIATE " +
                                                    " RESTORE DATABASE OlgooDB FROM DISK='" + txtRestorePath.Text + "'WITH REPLACE " +
                                                    "ALTER DATABASE OlgooDB SET ONLINE";
            context.Database.CommandTimeout = 360;
            context.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, command);
        }
    }

Does anyone know how to fix this error? 有人知道如何解决此错误吗?

Thanks in advance. 提前致谢。

You are confused with connecting to Express instance and localdb . 您对连接Express instancelocaldb感到困惑。

Your first connection string is fine to connect to Express instance, OlgooDB database: connectionString="Data Source=.\\SQLEXPRESS; Initial Catalog = OlgooDB; Integrated Security=True; " providerName="System.Data.SqlClient" 您的第一个连接字符串可以连接到Express实例OlgooDB数据库: connectionString="Data Source=.\\SQLEXPRESS; Initial Catalog = OlgooDB; Integrated Security=True; " providerName="System.Data.SqlClient"

In this case the database is already attached, there is no need to attach it one more time, and it's not a RESTORE to give you an error, but your second connection string: 在这种情况下,数据库已被附加,无需再附加一次,它不是RESTORE错误的错误,而是第二个连接字符串:

"Data Source =.\SQLExpress;AttachDbFilename=|DataDirectory|\OlgooDB.mdf; Database=OlgooDB; Integrated Security=True;" providerName="System.Data.SqlClient"

Here you use the syntax to connect to localdb, where .mdf is not attached and you attach it when you connect to localdb 在这里,您使用语法连接到localdb,其中未附加.mdf,并且在连接到localdb时将其附加

Of course when you try to CREATE DATABASE FOR ATTACH it fails because the database already exists. 当然,当您尝试为连接创建数据库时,它会失败,因为数据库已经存在。

So your connection string N2 is wrong: if you use localdb, you attach .mdf just before you use it. 因此,您的连接字符串N2是错误的:如果使用localdb,则在使用.mdf之前附加它。 But what you use is instead a database permanently attached, and you do not need to attach it 但是,您使用的是永久连接的数据库,而无需附加数据库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM