Introduction
I
wrote this article; https://www.codeproject.com/Articles/1091333/Build-persisting-Layer-with-ASP-NET-Core-and-EF-Co when the framework Core 1.0 was introduced as
a stable version. But now, we have a lot
of changes in the current version Core 2.1.
We
will focus on Code First approach in .Net Core 2.0.
So
let’s start by Prerequisite:
-
Visual
Studio 2017 v 15.5.x
-
SQL
Server 2014 / 2016 Server Management Studio with a default localdb.
-
PostgreSQL.
Contents
1.
Create
an ASP.NET Core Web Application : Samples.AspCoreEF
2.
Add
Class Library Core to the solution : Samples.AspCoreEF.DAL.EF
3.
Create
model classes: Task and Person.
4.
Add
Context : TaskSystemDbContext
5.
Register
the context class with Dependency Injection.
6.
Auto-Create
the database.
7.
Add
Web API controller and test using Postman.
Create an ASP.NET Core Web Application
We
suppose that we created our Database as the previous article.
We
Open Visual Studio > File > New Project> Select “ASP.NET Core Web
Application” > Enter Name “Samples.AspCoreEF” & Location > OK.
Afterwards,
we will select the template “Web Application” and we confirm the choice by
clicking OK. This project will be the presentation layer of this sample that
includes the razor pages and individual classes (.cs) as a code behind, and in
next part, we will add the new project that will contain the EF Core 2.0 and
will be added as a reference to the presentation Layer, in this way we ensure a
separation of Concern.
Add Class Library Core to the solution -
Samples.AspCoreEF.DAL.EF
We
Open Visual Studio > File > New Project> Select “Class Library (.NET
Core)” > Enter Name “Samples.AspCoreEF. DAL.EF” & Location > OK.
The
project Samples.AspCoreEF.DAL.EF will contain our Entity Framework models,
migrations, and context.
In
the previous article, we have two models: Person and Task, we will use the
same:
We install the Entity Framework Core package for the
database provider (EF Core DB Provider) from NuGet Package Manager Console in
Visual Studio 2017
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.0.1
Or we just open
the Search with Microsoft.EntityFrameworkCore.SqlServer
in Nuget Package Manager and we click on Install:
We
do the same for PostgreSQL; we will add Npgsql.EntityFrameworkCore.PostgreSQL,
Npgsql.EntityFrameworkCore.PostgreSQL.Design
reference to the project from NuGet Package Manager Console in Visual Studio
2017
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL -Version 2.0.1
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.Design -Version
1.1.1
We
need to install the Entity Framework
Tool to run EF Core Commands like migrations,
scaffolding, etc. So, we will add Microsoft.EntityFrameworkCore.Tools
package
Or: Install-Package
Microsoft.EntityFrameworkCore.Tools -Version 2.0.1
We
finish by installing this design package: Microsoft.VisualStudio.Web.CodeGeneration.Design
Add Context: TaskSystemDbContext
We
have to add a new folder called EntityFramework, where we will add our context,
as given below.
So,
we will have this structure:
Register the context class with
Dependency Injection
We
will work now in ASP.NET Web Application to be able to register our context.
We
will start by adding Samples.AspCoreEF.DAL.EF as a reference to
Samples.AspCoreEF.
Afterwards,
we will add the needed references to generate our database as before.
In
the Startup.cs, we will add two blocks to show you how we can register context
class in two different ways. Thus, this method looks like:
1. public void ConfigureServices(IServiceCollection services)
2. services.AddMvc();
We
will add this block related to the connection to SQL Server database.
1. //Using SQL Server
2. var sqlconnection = @"Server=(localdb)\v11.0;Database=samplecoreEF;Trusted_Connection=True;";
3. services.AddDbContext<TaskSystemDbContext>(dbcontextoption => dbcontextoption.UseSqlServer(sqlconnection));
SQLconnection
is a hardcoded string and we use UseSQLServer to connect to the database.
In
ASP.NET Core, we use store configuration string in a Json file: appsettings.json.
Thus,
we will call it in Startup.cs in the given way.
1. //Using Postgresql
2. var connectionString = Configuration["DbContextSettings:ConnectionString"];
3. services.AddDbContext<TaskSystemDbContext>(
4. opts => opts.UseNpgsql(connectionString)
5. );
Tools
- NuGet Package Manager and then we click on Package Manager Console menu.
Type
Add-Migration CoreMigration and enter this is used to scaffold a migration by
creating the initial tables for every model. If we get an error like this
message “The term 'add-migration' is not recognized as
the name of a cmdlet”, please close and reopen Visual Studio.
If
we check the databases, we will find the tables are added automatically.
If
the database exists, we use Update-database to apply the new migration to the
database.
Add
Web API controller and test, using Postman.
Now,
we will add new API Controller called PersonController.
Conclusion
In
this article, I tried to show how we can build the same project using the
framework Core 2.0 instead of Core 1.0 by showing the difference and the change
made between these versions. I used the same database for SQL Server or
PostgreSQL.
We
created the same classes but the migration and the references were changed. In
our sample, we ensured the separation of Concern by creating a separate layer
(Persistence Layer) that contains our entities and the migration part. We just
covered the Code First approach. For the ORM EF the top-level APIs remain the
same between these versions.