c# - 在运行时更改 DbContext 连接

标签 c# database entity-framework reflection entity

我有 3 个数据库要使用:A、B 和 C。 每个都有相同的表(例如:用户、产品)。

我想让用户决定(在运行时)他想使用哪个数据库。 所以...我使用 EF5 并创建了 3 个 edbx 文件,这些文件创建了以下类:ADBEntities、BDBEntities 和 CDBEntities。

我怎样才能让他决定 selecteddb 以便我可以获得它的用户?

我的意思是,

var dstuff = from user in selecteddb.users
             where user.UserEmail == userEmail
             select user.UserID;

我曾考虑过使用反射/基类 (DBEntities),但没有深入了解这些想法。

最佳答案

这个答案有点晚了,但我认为有一种潜在的方法可以用一种简洁的小扩展方法来做到这一点。正如 slypete(好听的名字 :-))所说,假设所有表/属性都相同,您只需要一个类模型。在这种情况下,我们可以利用 EF 约定优于配置加上一些小的框架调用。

话不多说,注释代码和示例用法:

扩展方法类:

public static class ConnectionTools
{
    // all params are optional
    public static void ChangeDatabase(
        this DbContext source,
        string initialCatalog = "",
        string dataSource = "",
        string userId = "",
        string password = "",
        bool integratedSecuity = true,
        string configConnectionStringName = "") 
        /* this would be used if the
        *  connectionString name varied from 
        *  the base EF class name */
    {
        try
        {
            // use the const name if it's not null, otherwise
            // using the convention of connection string = EF contextname
            // grab the type name and we're done
            var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
                ? source.GetType().Name 
                : configConnectionStringName;

            // add a reference to System.Configuration
            var entityCnxStringBuilder = new EntityConnectionStringBuilder
                (System.Configuration.ConfigurationManager
                    .ConnectionStrings[configNameEf].ConnectionString);

            // init the sqlbuilder with the full EF connectionstring cargo
            var sqlCnxStringBuilder = new SqlConnectionStringBuilder
                (entityCnxStringBuilder.ProviderConnectionString);

            // only populate parameters with values if added
            if (!string.IsNullOrEmpty(initialCatalog))
                sqlCnxStringBuilder.InitialCatalog = initialCatalog;
            if (!string.IsNullOrEmpty(dataSource))
                sqlCnxStringBuilder.DataSource = dataSource;
            if (!string.IsNullOrEmpty(userId))
                sqlCnxStringBuilder.UserID = userId;
            if (!string.IsNullOrEmpty(password))
                sqlCnxStringBuilder.Password = password;

            // set the integrated security status
            sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;

            // now flip the properties that were changed
            source.Database.Connection.ConnectionString 
                = sqlCnxStringBuilder.ConnectionString;
        }
        catch (Exception ex)
        {
            // set log item if required
        }
    }
}

用法:

// assumes a connectionString name in .config of ADBEntities
var selectedDb = new ADBEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDb.ChangeDatabase
    (
        initialCatalog: "name-of-bdb-initialcatalog",
        userId: "jackthelad",
        password: "nosecrets",
        dataSource: @".\sqlexpress" // could be ip address 100.23.45.67 etc
    );

我目前正是出于您上面提到的目的使用它,到目前为止,它对我来说非常有用。希望对您有所帮助。

关于c# - 在运行时更改 DbContext 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20222935/

相关文章:

javascript - 提交表单后禁用重定向

c# - 使用 ScaleTransform 和 TranslateTransform 在 WPF 图像控件的显示区域中显示图像的一部分

php - 注册表格的电子邮件激活

c# - "System is undefined"使用点击处理程序时出现 JavaScript 错误?

c# - 无法正确实现对象属性值与控件属性值的绑定(bind)

javascript - Symfony 3.4 如何将 Javascript 数据传递给 Controller ​​?

mysql - 查询以获取开始日期和结束日期之间的重复客户

c# - 尝试使用 LINQ 方法语法将 GroupBy 与多个属性一起使用时出现问题

mysql - Entity Framework - 外键名称

c# - 使用 Asp.Net 身份数据库第一种方法