实体框架 – EF6 DBContext动态连接字符串

前端之家收集整理的这篇文章主要介绍了实体框架 – EF6 DBContext动态连接字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public partial class ProcessContext : DbContext
{
    static ProcessContext()
    {
        Database.SetInitializer<ProcessContext>(null);
    }

    public ProcessContext()
        : base("Name=ProcessCS") //Comes from Config File
    {
    }

    --DBSets 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       --Code
    }
}

这是一个多用户数据库,我们有3个不同的数据库。集中DB位于公共位置,不会更改。这是DB存储的其他细节。我需要创建连接字符串@运行时,其细节将来自此集中式数据库。有人可以让我知道怎么去吗?

我尝试使用以下代码,但它不工作。这个方法将在这里调用

public ProcessContext()
    : base(nameOrConnectionString: ConnectionString())
{
}

private static string ConnectionString()
{
    sqlConnectionStringBuilder sqlBuilder = new sqlConnectionStringBuilder();
    sqlBuilder.DataSource = "XXX";
    sqlBuilder.InitialCatalog = "YYY";
    sqlBuilder.PersistSecurityInfo = true;
    sqlBuilder.IntegratedSecurity = true;
    sqlBuilder.MultipleActiveResultSets = true;

    EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
    entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
    entityBuilder.Metadata = "res://*/";
    entityBuilder.Provider = "System.Data.sqlClient";

    return entityBuilder.ToString();
}

解决方法

对于sql Server连接,覆盖实体容器类:(在EF6中工作,sql Server 2012 express,VS2013)
public partial class PxxxxEntities
{
    private PxxxxEntities(string connectionString)
        : base(connectionString)
    {
    }

    public static PxxxxEntities ConnectTosqlServer(string host,string catalog,string user,string pass,bool winAuth)
    {
        sqlConnectionStringBuilder sqlBuilder = new sqlConnectionStringBuilder
        {
            DataSource = host,InitialCatalog = catalog,PersistSecurityInfo = true,IntegratedSecurity = winAuth,MultipleActiveResultSets = true,UserID = user,Password = pass,};

        // assumes a connectionString name in .config of MyDbEntities
        var entityConnectionStringBuilder = new EntityConnectionStringBuilder
        {
            Provider = "System.Data.sqlClient",ProviderConnectionString = sqlBuilder.ConnectionString,Metadata = "res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl",};

        return new PxxxxEntities(entityConnectionStringBuilder.ConnectionString);
    }
}
原文链接:https://www.f2er.com/aspnet/252591.html

猜你在找的asp.Net相关文章