In the last post I described how to configure Entity Framework in an ASP.NET Core Project.In this post I’ll show how to create and configure a DbContext.

First I’m going to create InvestipsDbContext and derived from DbContext, import the namespace Microsoft.EntityFrameworkCore, the way to configure the DbContext has changed in entity framework core

public contructorName (string connectionString): base(connectionString){}

Entity Framework core is design in a more loosely couple fashion and in decouple from System.Configuration. ConfigurationManager class

Instead we need to pass the connection string explicitly.

Now in EF Core

We have to pass DbContextOptions which is a new generic class accepting as a parameter the type of our context. DbContextOptions<InvestipsDbContext> in my example

public InvestipsDbContext(DbContextOptions<InvestipsDbContext> options)
            : base(options){}

Now we need to register this DbContext as a service for dependency injection so we in the future can inject it like this.

public PorfolioRepository(InvestipsDbContext context
     this.context = context;

Now in Startup.cs class under ConfigureServices method that is where we register our dependencies in Asp.Net core

Services which is an IServiceCollection or the container for all the dependencies in our application

Here we have a method AddDbContext, this method is generic and the parameter is the type of our context InvestipsDbContext

Here we are going to use a lambda expression that determine what persistent store we are going to use and the connections string.

services.AddDbContext<InvestipsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

UseSqlServer is an extension method under Microsoft.EntityframeworkCore.

Here we are getting the connection string from appsettings.json file

  "ConnectionStrings": {
    "Default": "server=localhost; database=investips; user id=sa; password=MyComplexPassword!234"
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"