Reputation: 31
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.
Upvotes: 0
Views: 1731
Reputation: 527
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.
Upvotes: 3