Building Entity framework Core DbContext Options

Hi. In certain circumstances, you may want to create the Entity framework core DbContext options manually. I'll show you how to achieve it.

First, as we can see in the summary of the DbContextOptions<TContext> class, this class is not designed to be constructed directly. 

Summary of DbContextOptions<TContext> class

Initializes a new instance of the DbContextOptions<TContext> class. You normally override DbContext.OnConfiguring(DbContextOptionsBuilder) or use a DbContextOptionsBuilder<TContext> to create instances of this class, and it is not designed to be directly constructed in your application code.

Instead, you have to make use of the DbContextOptionsBuilder<TContext> class to create an instance of the DbContextOptions<TContext> class. And here is how you do it.

Step 1. Create an instance of the DbContextOptionsBuilder<TContext> class.

var dbContextOptionsBuilder = new DbContextOptionsBuilder<HrlibContext>();

Step 2. Configure the required options. For example, let us configure to use SQL server here. (Remember to replace your connection string).

dbContextOptionsBuilder.UseSqlServer("Data Source=(localdb)\\test;Integrated Security=true;");

Step 3. When you are done with configuring your options, you can call the Options member of the builder class to get the instance of the DbContextOptions<TContext> class.

var dbContextOptions = dbContextOptionsBuilder.Options;

One liner

DbContextOptions<HrlibContext> options = new DbContextOptionsBuilder<HrlibContext>().UseSqlServer("Data Source=(localdb)\\test;Integrated Security=true;").Options;

Then you have your options.

I hope this helps you.