I am new to EF using EF4 with Database First and generation taking place.
I have to place the connection string in a different config than the app.config.
How can I do it? How can I bypass it?
I have a partial class of MyTextContext
and I have a method like this
public static string GenerateConnectionString()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = dbServer;
sqlBuilder.InitialCatalog = dbName;
sqlBuilder.UserID = "YOUR_USERNAME";
sqlBuilder.Password = "YOUR_PASSWORD";
sqlBuilder.IntegratedSecurity = false;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
var entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = @"res://*/myTestModel.csdl|
res://*/myTestModel.ssdl|
res://*/myTestModel.msl";
return entityBuilder.ToString();
}
I have noticed that my EFModel.designer has a constructor like these:
/// <summary>
/// Initializes a new MyTestContext object using the connection string found in the 'MyTestContext' section of the application configuration file.
/// </summary>
public MyTestContext() : base("name=MyTestContext", "MyTestContext")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new MyTestContext object.
/// </summary>
public MyTestContext(string connectionString) : base(connectionString, "MyTestContext")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new MyTestContext object.
/// </summary>
public MyTestContext(EntityConnection connection) : base(connection, "MyTestContext")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
How can I use my “GenerateConnectionString” rather then EF reading from the app.config?
Thanks for any suggestions
Did you try using the 2nd ctor overload?
e.g
From MSDN:
So in theory, it should use the one you supply (unless you use the parameterless constructor).
I’ve never tried this though (i don’t use code generation, i hand craft everything).