Reputation: 4406
I got this idea from here. It converts an old style connection string to a modelFirst Connection string:
public static class ConnectionStringExtensions
{
public static string GetEntityConnectionString(this string connectionString, Type contextType)
{
var prefix = contextType.Namespace.Replace(contextType.Assembly.GetName().Name, "");
if (prefix.Length > 0
&& prefix.StartsWith("."))
{
prefix = prefix.Substring(1, prefix.Length - 1);
}
if (prefix.Length > 1 && !prefix.EndsWith("."))
{
prefix += ".";
}
var csBuilder = new EntityConnectionStringBuilder
{
Provider = "System.Data.SqlClient",
ProviderConnectionString = connectionString,
Metadata = String.Format("res://{0}/{1}.csdl|"
+ "res://{0}/{1}.ssdl|"
+ "res://{0}/{1}.msl"
, contextType.Assembly.FullName
, prefix + contextType.Name)
};
return csBuilder.ToString();
}
}
This works great. My question is when I call it:
string connString = ConfigurationMananager.ConnectionStrings["name"].ConnectionString;
var dbContext = new MyDbContext(connString.ToEntityConnectionString(typeof(MyDbContext);
The call looks redundant with the instantiation and then passing the type into the extension method. Is there a way to get that programatically based on what constructor it was passed into
Upvotes: 0
Views: 84
Reputation: 581
I'm afraid it isn't possible.
You'll need to send the DbContext type to the method some way, or turn it into an constant inside your class.
I don't know how to get the type of the caller from inside a method, and I think it's a bad idea. That will be a collateral effect inside the method. If the DbContext is needed for the processing, it should be in the method signature. If you'll never change it, it should be a constant.
You can try to send the type using "this.GetType()" or var dbContext = connString.GetEntityConnectionString(this.GetType()).
Upvotes: 1