gpt4 book ai didi

c# - 使用 EF6 在运行时连接到 SQL Server - 部分类构造函数问题

转载 作者:行者123 更新时间:2023-11-30 23:24:02 25 4
gpt4 key购买 nike

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

EF6 DBContext Dynamic Connection String

我已经按照上面的说明设置了我的部分类

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 但是你试图调用私有(private)的构造函数.您创建类(class)的方式没有任何问题。问题在于您尝试调用该类的方式。

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

关于c# - 使用 EF6 在运行时连接到 SQL Server - 部分类构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com