实体框架5 - 计算数据库是sql server还是sql CE(精简版)

时间:2013-06-13 06:51:21

标签: entity-framework sql-server-ce

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

2 个答案:

答案 0 :(得分:1)

这非常复杂!

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

答案 1 :(得分:1)

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

return context.Database.Connection is SqlCeConnection;