How to Backup and Restore MS-SQL Database in Entity Framework C#?



Entity Framework is anORM object-relational mapper designed to handle interactions with single entities and short lists of entities. It's neither designed for bulk operations, nor is it a server admin framework. So NO - I don't think you can do this using Entity Framework 

But if you want to develop entity framework backup and restore you want to go through windows form application.





Step 1:-

Frist you want to get pc name for make connection string.
    Example: - connection string = pc-name/SQLEXPRESS
     (Most of computer ms-sql default connection path)

If this database is a remote database we can use ip address
Connection string = ip-addresss/SQLEXPRESS

String Connection_string= System.Environment.MachineName.ToString ();



Step 2:-

Next we want to make a new connection with database to backup & restore.

To open new connection
· Open sql connection
· Make sql command
· Make a readable sql command


private SqlConnection conn;
private SqlCommand command;
private SqlDataReader reader;
try
            {
               
ConnectionString = "Data Source = " +connection_string+"\\SQLEXPRESS;Integrated Security=True “;
                conn = new SqlConnection(ConnectionString);
                conn.Open();
                     sql = "sp_databases";
                command = new SqlCommand(sql, conn);
                reader = command.ExecuteReader();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
       
To disconnect the connection
conn.Close();


Step 3:-

Then make the backup using the connection.
Path=string path to store the backup


try
            {

                conn = new SqlConnection(ConnectionString);
                conn.Open();
   sql = "BACKUP DATABASE EntityModel TO DISK ='" + Path  + "\\EntityModel-" + DateTime.Now.Ticks.ToString() + ".bak' ";
                command = new SqlCommand(sql, conn);
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }



Step 4:-

Then make the Restore using the connection.
Path=string path to selected path of previous backup

try
            {

                conn = new SqlConnection(ConnectionString);
                conn.Open();
                sql = "Alter Database EntityModel Set SINGLE_USER WITH ROLLBACK IMMEDIATE; Restore Database EntityModel FROM Disk= '" + path + "' WITH REPLACE;";
                command = new SqlCommand(sql, conn);
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }


Warning:-
After executing this code the programmer database convert to single user mode concert to multi user mode

Comments

Popular Posts