2017-09-21 57 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; 
}