c# - Entity Framework MySQL DbContext 无法连接

标签 c# mysql sql-server entity-framework dbcontext

我使用代码优先创建了一个模型,没有在 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/

相关文章:

php - Ubuntu Linux VPS 上的 SQLSTATE[01002] Adaptive Server 连接失败(严重性 9)错误

c# - 服务层(.NET 应用程序)中的授权和用户信息

c# - 我应该为简单的控制台应用程序使用 C# 命名空间吗?

c# - Css 未在浏览器中执行

c# - 如何将 C# 函数指针传递给 CLI/C++ 代码?

php - 编辑用户的帐户详细信息

php - 检查sql数据库中是否存在email,然后输出(关于running if inside if)

mysql - 从 CSV 插入多个表

sql - 将序列号转换为日期

sql-server - SQL Server 逆透视两列