Friday, October 18, 2019

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

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

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

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.

UseSqlServer is an extension method under Microsoft.EntityframeworkCore.

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