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?
35
votes
2 Answers
62
votes
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.