2017-09-21 54 views
1

我创建利用二维码的第一个模型,并没有App.config中存储的密码,我通过它的DbContext的构造来代替:实体框架的MySQL的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).

我试图记住我的班级为未来:

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

它并没有帮助。

+0

你能告诉我们你的连接字符串吗?用****标记你的密码 –

+0

你有没有做过什么错误问你?你有没有检查这是否是正确的连接字符串和您的服务器正在运行? –

+0

@Matthias Burger,server = localhost; user id = test_user1; password = ****; database = tasks_for_consultants –

回答

0

正如你已经自己找到了解决办法,我添加了答案:

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

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