DbContext persistence with static method based on

2019-09-09 10:52发布

I have a DbContext class in which I want to set the proper environment connection string only once as long as the console application is running.

public class RPMContext : DbContext {    
    public RPMContext(string nameOrConnectionString)
        :base(nameOrConnectionString) {
    }  
}

Then it would be called up with

 private RPMContext db = new RPMContext("name=LH_RPMContext");

However I need to persist a static global method of this so that I can count on the persistence of the lifetime of the running console application that it does not go away

I was having a menu system like this

 Console.WriteLine("Select Environment:\n");
 Console.WriteLine("1. Localhost");
 Console.WriteLine("2. DEV");
 Console.WriteLine("3. QA");
 Console.WriteLine("4. Day 1");
 Console.WriteLine("5. Production\n");
 Console.Write("Number: ");
 byte environment = byte.Parse(Console.ReadLine());

So I suppose that if the user picked 2 which is "DEV" then

 var dev_db = new RPMContext("name=DEV_RPMContext");

However later on when I am doing all sorts of CRUD operations with Entity Framework, I will want to instantiate it again ... so thus I will just want to hold that value in memory then, right?

So maybe some enum with these values like DEV_RPMContext and then set it ?

Here was my other question: Passing string into a Constructor of DbContext with a Base class is not setting the value

1条回答
我命由我不由天
2楼-- · 2019-09-09 11:42

One option is to edit your DbContext template like this:

public class RPMContext : DbContext {
    public static string DefaultConnectionString;
    public RPMContext():base(DefaultConnectionString) {
    }   
    public RPMContext(string nameOrConnectionString)
        :base(nameOrConnectionString) {
    }  
}

Then when choice is made, assign selected connection string:

RPMContext.DefaultConnectionString = "your connection string";

And then just instantiate context as usual:

using (var ctx = new RPMContext()) {
// uses default connection string here
}
查看更多
登录 后发表回答