0

enter image description here

I am little bit confused - I am creating a Windows Presentation Foundation (WPF) application for my local client, and client wants a backup and restore database facility

I am using SQL Server with Entity Framework using a database-first approach; language is C#.

Please guide me how I can do this via C# code.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rizwan
  • 31
  • 5
  • 1
    See http://www.codeproject.com/Articles/123441/SQL-Server-Backup-and-Restore-Databases-using and http://www.codeproject.com/Articles/14848/Using-SMO-for-Backup-Restore-and-Security-Purposes for starters – marc_s Jul 31 '16 at 10:03

1 Answers1

3

You will have to use the BACKUP and RESTORE commands of TSQL and invoke them via an SqlCommand object, like in the example below:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateBackup("Server=localhost\\bekidev;Database=ApplifyAengine;Trusted_Connection=True;MultipleActiveResultSets=true",
                "test", 
                "C:\\temp\\test.bak");
        }

        private static void CreateBackup(string connectionString, string databaseName, string backupFilePath)
        {
            var backupCommand = "BACKUP DATABASE @databaseName TO DISK = @backupFilePath";
            using (var conn = new SqlConnection(connectionString))
            using (var cmd = new SqlCommand(backupCommand, conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@databaseName", databaseName);
                cmd.Parameters.AddWithValue("@backupFilePath", backupFilePath);
                cmd.ExecuteNonQuery();
            }
        }
    }
}

To do a restore, use the TSQL RESTORE command.

Please note that SQL Server backup and restore is a very large topic, you should dive into the theory behind it and carefully map your specific situation and requirements to the available features.

tomislav_t
  • 527
  • 2
  • 9