使用 EF6 在运行时连接到 SQL 服务器 - 部分 Class 构造函数出现问题

Connecting to SQL Server at Runtime using EF6 - Issue with Partial Class Constructor

我能够使用这篇文章到达某个地方,

EF6 DBContext Dynamic Connection String

我已经按照上述说明设置了部分 class

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);
    }
}

虽然我无法使用 ConnectToSqlServer 方法启动。

尝试 1:

public PxxxxEntities database = new PxxxxEntities(PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true));     

'PxxxxEntities' does not contain a constructor that takes 1 argument

尝试 2:

public PxxxxEntities database = new PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true);  

The type name 'ConnectToSqlServer' does not exist in the type 'PxxxxEntities'

(根据 Crowcoder 评论)

尝试 3:将构造函数设置为 public

public PxxxxEntities database = new PxxxxEntities(PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true)); 

Cannot convert from model.PxxxxEntities to 'string'

(根据恩科西) 尝试 4:

public PxxxxEntities database = PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true);

Additional information: Unable to load the specified metadata

需要做一点小改动,

使用 Web.Config 中的元数据更新方法中的元数据。解决附加信息:无法加载指定的元数据

成功!!

你的 DbContext 的构造函数是 private 并且你有一个 static 工厂方法 ConnectToSqlServer 但你试图调用私有的构造函数。您创建 class 的方式没有任何问题。问题是您如何尝试调用 class.

public PxxxxEntities database = PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true);