WPF - How to Backup / Restore LocalDB Programmatically - ClickOnce

前端 未结 2 1220
遇见更好的自我
遇见更好的自我 2021-01-15 04:18

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

2条回答
  •  礼貌的吻别
    2021-01-15 04:30

    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);
                dbEntities.Database.SqlQuery(backupQuery).ToList().FirstOrDefault();
            }
        }
    
        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(restoreQuery).ToList();
                var resut = list.FirstOrDefault();
            }
        }
    
    
    

    Hope this is what you want.

    提交回复
    热议问题