2

在過去的幾個小時裏,我一直在研究這個問題,發現許多類似的話題,但他們似乎都沒有幫助。更改EF連接字符串給出 - 不支持關鍵字:'元數據'

我有一個使用Entity Framework 5一個C#應用程序,我有使用從應用程序配置文件中的連接字符串時工作正常,一個.edmx數據模型。現在

我想在運行時更改連接字符串,但它拋出了說一個例外:不支持

關鍵詞:「元數據」。

這裏是我的代碼:

private string GetNewConnectionString(string server, string database, string username, string password) 
{ 
    var sqlBuilder = new SqlConnectionStringBuilder() 
    { 
     DataSource = server, 
     InitialCatalog = database, 
     UserID = username, 
     Password = password, 
     IntegratedSecurity = true, 
     MultipleActiveResultSets = true 
    }; 

    var entityBuilder = new EntityConnectionStringBuilder() 
    { 
     Provider = "System.Data.SqlClient", 
     ProviderConnectionString = sqlBuilder.ToString(), 
     Metadata = "res://*/MyTestModel.MyTestModel.csdl|res://*/MyTestModel.MyTestModel.ssdl|res://*/MyTestModel.MyTestModel.msl" 
    }; 

    return entityBuilder.ToString(); 
} 

public void insertInDB() 
{ 
    var newConnectionString = GetNewConnectionString(server, database, username, password); 
    //newConnectionString = newConnectionString .Replace("\"", """); // doesn't help 
    //newConnectionString = newConnectionString .Replace("\"", "'"); // doesn't help either 

    using (var context = new MyTestModel.MyEntities(newConnectionString)) // it crashes here 
    { 

    } 
} 

元數據應該是正確的,因爲我已經從應用程序配置文件複製它,另外,如果我的newConnectionString值複製到應用程序配置並使用它,它工作正常,如果我用"替換報價。

這是newConnectionString值(我只替換一些虛擬憑證的憑證):

元數據= RES:// /MyTestModel.MyTestModel.csdl|res:///MyTestModel.MyTestModel.ssdl | res://*/MyTestModel.MyTestModel.msl; provider = System.Data.SqlClient; provider connection string =「Data Source = myServer; Initial Catalog = myDatabase; Integrated Security = True; User ID = myDbUser; Password = myDbUserPassword; MultipleActiveResultSets = True「

我看不出有什麼問題,任何人都可以發現什麼?

+0

您正在使用錯誤的提供程序。如果你想連接工作使用* System.Data.EntityClient *而不是System.Data.SqlClient – rene

+0

另一個人有同樣的問題:http://stackoverflow.com/a/25041876/609176 –

+0

@rene我試過,但那麼它會給出另一個例外 - '在配置中找不到指定的商店提供商,或者無效。' – Apostrofix

回答