栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

实体框架在运行时更改连接

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实体框架在运行时更改连接

这个答案有点晚了,但是我认为有一种潜在的方法可以使用一种简洁的扩展方法来做到这一点。我们可以在配置之外加上一些小的框架调用,而利用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 = "")             {        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 MyDbEntitiesvar selectedDb = new MyDbEntities();// so only reference the changed properties// using the object parameters by nameselectedDb.ChangeDatabase    (        initialCatalog: "name-of-another-initialcatalog",        userId: "jackthelady",        password: "nomoresecrets",        dataSource: @".sqlexpress" // could be ip address 120.273.435.167 etc    );

我知道您已经具备基本功能,但是认为这样做会增加一些多样性。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/378788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号