简体   繁体   中英

Changing the EF connection string gives - Keyword not supported: 'metadata'

For the past few hours I've been looking into this problem, found many similar topics but none of them seems to help.

I have a C# application that uses the Entity Framework 5 and I have a .edmx data model that works fine when using the connection string from the app config file.

Now I would like to change the connection string during runtime, but it throws an exception that says:

Keyword not supported: 'metadata'.

Here is the code that I have:

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
     {

     }
 }

The metadata should be correct, because I have copied it from the app config file, also if I copy the value of newConnectionString to the app config and use it, it works fine if I replace the quotations with " .

This is the value of newConnectionString (i've only replaced the credentials with some dummy credentials):

metadata=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"

I cannot see what is wrong with it, can anybody spot something?

This answer: Entity Framework change connection at runtime solves the problem

I cannot understand what the problem with my code was, but it works fine with the extension method from the link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM