none
how to backup a service based database with dbcontext

    Question

  • I'm creating a winform application with c#, and I use the service-base database to create a local database, and use entity framework to manipulate it, and my questinn is how to backup and restore this service-base database with entity framework, my code doesn't work and the hint is my database name does not exist:

            private void openDataBackup_Click(object sender, EventArgs e)
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                folderBrowserDialog.Description = "选择备份文件夹";
                folderBrowserDialog.ShowNewFolderButton = true;
                folderBrowserDialog.RootFolder = Environment.SpecialFolder.Personal;
                DialogResult result = folderBrowserDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    string folderName = folderBrowserDialog.SelectedPath;
                    if (folderName != "")
                    {
                        using (var context = new WarehouseManagementSystemDBEntities())
                        {
                            string dbname = "WarehouseManagementSystemDB";
                            string filename = folderName + "\\backup.bak";
                            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Suppress))
                            {
                                context.Database.UseTransaction(null);
                                string sqlCommand = @"BACKUP DATABASE [{0}] TO  DISK = N'{1}' WITH NOFORMAT, NOINIT,  NAME = N'MyAir-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
                                context.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction,
                                    string.Format(sqlCommand, dbname, filename));
                            }
                        }
                    }
                }
            }

    Monday, May 12, 2014 4:16 PM

Answers