问题
I have decide out of a business need to make a change to my DbContext class
Previously my code looked like this:
public class RPMContext : DbContext
{
public RPMContext() : base(ConnectionString()) { }
private static string ConnectionString(string connection)
{
conn = ConfigurationManager.ConnectionStrings["LH_RPMContext"].ConnectionString;
return conn;
}
}
Above "Works" but I need to be able to PASS in a string in which I'm able to set the static method ConnectionString to OTHER specified connection strings
So Thus my NEW code started down a path of NOT use base
public class RPMContext : DbContext
{
public RPMContext(string environment)
{
ConnectionString(environment);
}
private static string ConnectionString(string connection)
{
string conn;
if (connection == "LH")
{
conn = ConfigurationManager.ConnectionStrings["LH_RPMContext"].ConnectionString;
}
else
{
// dev , qa etc..
}
return conn;
}
}
PROBLEMS
I suppose this are several issue in which I'm not understanding that
- I need to be "setting the
DbContextin which thebasedoes that? - Do I NEED
basefor what I am doing? - Would
:this()be of benefit?
Previously I would instantiate with private RPMContext db = new RPMContext();
Now RPMContext("LH") and whatever string I wish /want to use.
Obviously with the current code, I'm getting "use of unassigned local variable conn"
回答1:
You are giving yourself unnecessary work.
DbContext already has a constructor that takes a full connection string or the name of the connection string in your config file.
public class RPMContext : DbContext {
public RPMContext(string nameOrConnectionString)
:base(nameOrConnectionString) {
}
}
if for example you have the following in your config file
<appSettings>
<add key="Environment" value="LH" />
</appSettings>
<connectionStrings>
<add name="LH_RPMContext" connectionString="..." providerName="System.Data.EntityClient" />
<add name="DEV_RPMContext" connectionString="..." providerName="System.Data.EntityClient" />
<add name="QA_RPMContext" connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>
You can create the DbContext you want by providing the name connection you want to use.
var db = new RPMContext("name=LH_RPMContext");
var dev_db = new RPMContext("name=DEV_RPMContext");
var qa_db = new RPMContext("name=QA_RPMContext");
or... based on some of your previous posts, you can do something like this...
public class RPMContext : DbContext {
public RPMContext()
:this(string.Format("name={0}_RPMContext",ConfigurationManager.AppSettings["Environment"])){}
public RPMContext(string nameOrConnectionString)
:base(nameOrConnectionString) {
}
}
来源:https://stackoverflow.com/questions/37537771/passing-string-into-a-constructor-of-dbcontext-with-a-base-class-is-not-setting