3

我有一个功能允许管理员创建和下载数据库备份文件(包括在下面,但不必阅读或遵循以回答问题)。有没有办法判断支持实体框架上下文的数据库是否是 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')
    }
}
4

2 回答 2

1

这出乎意料的复杂!

最简单的方法(又名 hack)是SELECT @@version使用DbContext.Database.SqlQuery(or DbContext.Database.ExecuteSqlCommand) 执行,如果失败则假设您正在运行 CE。

于 2013-06-13T12:51:52.557 回答
1

基于异常的正常程序流程不是一个好的模式,我提出这个简单的解决方案:

return context.Database.Connection is SqlCeConnection;
于 2013-06-18T19:48:04.900 回答