gpt4 book ai didi

c# - Entity Framework MySQL DbContext 无法连接

转载 作者:行者123 更新时间:2023-11-30 21:53:05 24 4
gpt4 key购买 nike

我使用代码优先创建了一个模型,没有在 App.config 中存储密码,而是将它传递给 DbContext 的构造函数:

public TasksWithoutPasswordContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
this.Database.Connection.ConnectionString = nameOrConnectionString;
}

但是我在尝试获取我的 DbContext 的 DbSet 时遇到运行时错误:

using (TasksWithoutPasswordContext contextWithoutPassword = new TasksWithoutPasswordContext(connectionString))
{
foreach (var user in contextWithoutPassword.users)
{
MessageBox.Show(user.user);
}
}

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).

我试图将我的类(class)标记为下一个:

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class TasksWithoutPasswordContext : DbContext

但这并没有帮助。

最佳答案

因为您已经自己找到了解决方案,所以我添加答案:

当您从 DbContext 继承并调用基础构造函数时,您可以使用默认基础构造函数(无参数构造函数)并在构造函数中设置连接字符串:

public TasksWithoutPasswordContext(string nameOrConnectionString) : base() 
{
this.Database.Connection.ConnectionString = nameOrConnectionString;
}

关于c# - Entity Framework MySQL DbContext 无法连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346909/

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