Mahdi Rashidi Mahdi Rashidi - 6 months ago 129
SQL Question

WPF - How to Backup / Restore LocalDB Programmatically - ClickOnce

I have an application which uses EF and LocalDB as it's database, published by ClickOnce.
it's my first time using LocalDB and I don't know how can i add a feature to my application to Backup/Restore The Database Programmatically.

My App Path Installed by ClickOnce :

C:\Users\Mahdi Rashidi\AppData\Local\Apps\2.0\NOL11TLW.9XG\CZM702AQ.LPP\basu..tion_939730333fb6fcc8_0001.0002_fd707bbb3c97f8d3

and This is the location which Database files Installed :

C:\Users\Mahdi Rashidi\AppData\Local\Apps\2.0\NOL11TLW.9XG\CZM702AQ.LPP\basu...exe_939730333fb6fcc8_0001.0002_none_8c555c3966727e7f

  1. How Should I Backup/Restore the Database?

  2. How Can I Keep Database Safe from ClickOnce further Updates?

Thanks alot :)


This is what I did for backup and restore of my localDb

public void BackupDatabase(string filePath)
        using (TVend2014Entities dbEntities = new TVend2014Entities(BaseData.ConnectionString))
            string backupQuery = @"BACKUP DATABASE ""{0}"" TO DISK = N'{1}'";
            backupQuery = string.Format(backupQuery, "full databsase file path like C:\tempDb.mdf", filePath);

    public void RestoreDatabase(string filePath)
        using (TVend2014Entities dbEntities = new TVend2014Entities(BaseData.ConnectionString))
            string restoreQuery = @"USE [Master]; 
                                                ALTER DATABASE ""{0}"" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
                                                RESTORE DATABASE ""{0}"" FROM DISK='{1}' WITH REPLACE;
                                                ALTER DATABASE ""{0}"" SET MULTI_USER;";
            restoreQuery = string.Format(restoreQuery, "full db file path", filePath);
            var list = dbEntities.Database.SqlQuery<object>(restoreQuery).ToList();
            var resut = list.FirstOrDefault();

Hope this is what you want.