我有一个功能允许管理员创建和下载数据库备份文件(包括在下面,但不必阅读或遵循以回答问题)。有没有办法判断支持实体框架上下文的数据库是否是 ce - 如果是这样,我将实施不同的备份策略(即,只需使用文件系统复制 .sdf 文件 - 尽管我必须想办法检查是否首先有任何打开的连接)。
谢谢你。
private const string dbBakDirectory = "~/App_Data/DbBackups/";
public const string versionFormat = "{0:yyyy-MM-dd HHmm}";
private const string namingFormat = "DAB Trial Database " + versionFormat;
private const string FullName = " FULL";
private const string DifferentialName = " (dif)";
public static int BackupDataBase(Database db, string dbName, string outputPath, bool differential=false)
{
if (!outputPath.EndsWith(".bak")) { outputPath += ".bak"; }
int sqlReturn = db.ExecuteSqlCommand(
"BACKUP DATABASE [" + dbName + "] TO DISK = N'" + outputPath + "' WITH " + (differential ? "DIFFERENTIAL," : "") + " CHECKSUM");
if (sqlReturn != -1) { return sqlReturn; }
return db.ExecuteSqlCommand("RESTORE VERIFYONLY FROM DISK = N'" + outputPath + "'");
}
public string CreateDbBackup(bool differential = false)
{
string outputFileName = Path.Combine(HostingEnvironment.MapPath(dbBakDirectory), string.Format(namingFormat, DateTime.Now) + (differential ? DifferentialName : FullName));
SqlConnectionStringBuilder conStr = new SqlConnectionStringBuilder();
using (DbContext context = new DataContext())
{
conStr.ConnectionString = context.Database.Connection.ConnectionString;
BackupDataBase(context.Database, conStr.InitialCatalog, outputFileName, differential);
}
return outputFileName;
}
编辑
感谢qujck,我现在正在使用
using (DbContext context = new DataContext())
{
conStr.ConnectionString = context.Database.Connection.ConnectionString;
string version = SqlVersion(context.Database).ToLower();
if (version.Contains("compact"))
{
string inputFileName = conStr.DataSource.Replace("|DataDirectory|", HostingEnvironment.MapPath("~/App_Data/"));
System.IO.File.Copy(inputFileName, outputFileName + ".sdf");
}
else
{
BackupDataBase(context.Database, conStr.InitialCatalog, outputFileName, differential);
}
}
public static string SqlVersion(Database db)
{
try
{
return db.SqlQuery(typeof(string), "SELECT @@version").Cast<string>().FirstOrDefault();
}
catch (System.Data.SqlServerCe.SqlCeException e)
{
return "Sql Server Compact Edition (version unspecified)";
// could also just return the data provider, return e.Source; ('Data Provider for Microsoft SQL Server Compact')
}
}