0
string dbname = _dbContext.Database.Connection.Database;

const string sqlCommand = @"BACKUP DATABASE [{0}] TO  DISK = N'{1}' WITH NOFORMAT,
    NOINIT,  NAME = N'MajesticDb-Ali-Full Database Backup',
    SKIP, NOREWIND, NOUNLOAD,  STATS = 10";

int path = _dbContext.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior
    .DoNotEnsureTransaction,
    string.Format(sqlCommand, dbname, "MajesticDB"));

I am using this code to make a database backup. It's working fine but this code is replacing the previous file with the new one. How do I change it so it doesn't?

4
  • what exactly is your question? Commented May 6, 2016 at 7:34
  • Are you overwriting db backup with the same name? Commented May 6, 2016 at 7:38
  • Yes its overwriting. I want to save new one every time Commented May 6, 2016 at 7:39
  • 1
    @RanaAli Add datetime with your db name. Commented May 6, 2016 at 7:41

2 Answers 2

2

Try like this.

string dbname = _dbContext.Database.Connection.Database;
string dbBackUp= "MajesticDB" + DateTime.Now.ToString("yyyyMMddHHmm");
const string sqlCommand = @"BACKUP DATABASE [{0}] TO  DISK = N'{1}' WITH NOFORMAT, NOINIT,  NAME = N'MajesticDb-Ali-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
int path= _dbContext.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, string.Format(sqlCommand, dbname , dbBackUp));
Sign up to request clarification or add additional context in comments.

3 Comments

This line is incorrect int path= _dbContext.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, string.Format(sqlCommand, dbBackUp, "MajesticDB"));
I think you meant to put dbBackUp and not "MajesticDB", since at the moment you are not renaming your database backup
@Draken Edit done. Typing mistake thanks for noticing. Sorry for late reply and edit.
1

you can try something like this:

string backupname= "MajesticDB" + DateTime.Now.ToString("yyyyMMddHHmm");
 const string sqlCommand = @"BACKUP DATABASE [{0}] TO  DISK = N'{1}' WITH NOFORMAT, NOINIT,  NAME = N'MajesticDb-Ali-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
       int path= _dbContext.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, string.Format(sqlCommand, dbname, backupname));

this way, to backup name "MajesticDB" is appended date and time, so every time you call your backup procedure, database will be backed up with different name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.