35
votes

I have a MVC 4 project set up and generated all the model classes using Entity Framework. Then I added a class and named it same as "MyProjectEntities" class and made it partial so I can add personalized methods in that class. I added bunch of methods to query database in this class and it builds fine. When I call these methods though I get UnintentionalCodeFirstException. I'm not sure what did I do wrong?

2

2 Answers

62
votes

You need to provide the correct connection string. Not just the normal "Data Source=" type strings.

You will have a connection string that starts with "metadata=" in your config file, use that one.

10
votes

You can also transform the simple connection string to a database-first connection string:

public static string BuildEntityConnectionStringFromAppSettings(string nameOfConnectionString)
{
    var shortConnectionString = GetConnectionStringByName(nameOfConnectionString);

    // Specify the provider name, server and database. 
    string providerName = "System.Data.SqlClient";

    // Initialize the connection string builder for the 
    // underlying provider taking the short connection string.
    SqlConnectionStringBuilder sqlBuilder =
        new SqlConnectionStringBuilder(shortConnectionString);

    // Set the properties for the data source.
    sqlBuilder.IntegratedSecurity = false;

    // Build the SqlConnection connection string. 
    string providerString = sqlBuilder.ToString();

    // Initialize the EntityConnectionStringBuilder.
    EntityConnectionStringBuilder entityBuilder =
        new EntityConnectionStringBuilder();

    //Set the provider name.
    entityBuilder.Provider = providerName;

    // Set the provider-specific connection string.
    entityBuilder.ProviderConnectionString = providerString;

    // Set the Metadata location.
    entityBuilder.Metadata = String.Format("res://*/Application.{0}.Data.Model.{0}Model.csdl|res://*/Application.{0}.Data.Model.{0}Model.ssdl|res://*/Application.{0}.Data.Model.{0}Model.msl", nameOfConnectionString);
    return entityBuilder.ToString();
}

Background: in my project there were many connection strings and we wanted to keep them simple and comparable.