简体   繁体   中英

Can't restore database with LocalDB

I have been using this code for about 2 years to restore 2008 r2 backup to 2008 r2 and it works every time. I am now trying to use the same code to restore from 2008 r2 backup to 2012 localdb and it fails every time. The error message is below. Not only does the restore fail, it leaves my current database in 'recovery pending' state, and is unusable. I am using c# and this must all be done programmatically with no user or DBA involvement. Can you help me get this thing back on track?

        using(var connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = String.Format("Alter Database {0} SET SINGLE_USER With ROLLBACK IMMEDIATE", dbName);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = connection;
            connection.Open();
            cmd.ExecuteNonQuery();

            SqlCommand cmd2 = new SqlCommand();
            cmd2.CommandText = String.Format(@"RESTORE DATABASE {0} FROM DISK = '{1}'", dbName, backupFilePath);
            cmd2.CommandType = CommandType.Text;
            cmd2.Connection = connection;
            cmd2.ExecuteNonQuery();
        }

System.Data.SqlClient.SqlException (0x80131904): The logical database file 'MyData_log' cannot be found. Specify the full path for the file. RESTORE could not start database 'MyData'. RESTORE DATABASE is terminating abnormally.

Edit: changed one line to

            cmd2.CommandText = String.Format(@"RESTORE DATABASE {0} FROM DISK = '{1}' WITH  FILE = 1, NOUNLOAD, REPLACE, STATS = 5", dbName, backupFilePath);

So far has made no difference.

Shouldn't you RESTORE DATABASE and use the WITH REPLACE option? And does your connection string connect you to the 'master' database for running these commands, rather than the database being restored?

Have you used SQL Server Management Studio to look at the database file name and locations for the *.mdf and *.ldf files?

I also find that sometimes the very FIRST restore of a database doesn't work as expected, but subsequent ones do... have you tried manually restoring the database (using SQL Server Management Studio... right-click the DB, tasks, restore database), and then tried running the code programmatically?

Generally, when doing restores programmatically, you want to grab the file names of the mdf and ldf files, and then specify them in the RESTORE command with the "WITH REPLACE" option.

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