简体   繁体   中英

“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".

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. choose a different database name. Cannot attach the file 'D:...\\bin\\Debug\\Database\\OlgooDB.mdf' as database '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 .

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"

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:

"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

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. But what you use is instead a database permanently attached, and you do not need to attach it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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