Using Entity Framework Core in a Separate Project

As we know separation of concern is important in any project. In ASP.NET Core using Entity Framework Core, in the same project is just not the right thing to do. So, In this Post, we will learn how to use Data Access Layer with ASP.NET Core.

Getting your gears together (Prepare Project for Entity Framework Core)

  • Create a New Console App project from .NET Core Section. Give some appropriate Name to Console App.
  • We need a Configuration file to store the database connection string and maybe some other settings. This configuration file should be available after building or publishing this application. To get things done follow below steps.
    • Add ‘appsettings.json’ file in the root of Console App.
    • Right click on ‘appsettings.json’ and select properties.
    • Under Advanced Settings set value Copy to Output Directory to Copy always.
  • Now open appsettings.json and add your database connection string.

  • When we run this application then appsettings.json will be copied to Debug or Release folder and we don’t have to copy it manually.

Add NuGet Packages

Alright, So now we need EF Core NuGet Packages to use Entity Framework Core and to use appsettings.json for settings. Open NuGet Package manager and install the following Packages.

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Json

Now, we are ready to start real work.

Create Database Context and Entities

Well, to make things simple I will use standard Student example to create my Entities.

Now, we have database context and simple entities in place.

Creating Database Context Factory Class

Before using database context we need an options object that will carry configuration. As we want things clean, we will create a Factory class that reads connection string from appsettings.json and creates options object which return already initialized database context.

 

We are throwing Exception if the connection string is missing. Which will be helpful while diagnosing the app crash.

Using Database Context in Console App

Finally, we are ready to use our DbContextFactory to create Database Context.

 

Using This Console App with ASP.NET Core

You can create repositories in this same Console App and then use it in ASP.NET Core project. But I am not going to Show how to create repositories. But I will simply show how to register this Console App with ASP.NET Core Project.

Open Startup.cs class in your ASP.NET Core Project and add following code inside ConfigureServices method. Now, you will be able to open a DbContext in ASP.NET Core Just like we did in Console App.

 

3 Replies to “Using Entity Framework Core in a Separate Project”

Leave a Reply

Your email address will not be published. Required fields are marked *