Build Persisting Layer With ASP.NET Core 2.0 And EF Core 2.0 Using Code First Approach

Introduction

I wrote this article when the .NET 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 the Code First approach in .NET Core 2.0.

So, let’s start with the prerequisites.

  • Visual Studio 2017 v 15.5.x
  • .NET Core 2.0. https://www.microsoft.com/net/download/all
  • 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

Suppose that we have created our Database as in the previous article.

Open Visual Studio > File > New Project> Select “ASP.NET Core Web Application” > Enter Name “Samples.AspCoreEF” & Location > OK.

ASP.NET Core

Afterward, we will select the template “Web Application” and we will 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 code behind, and in the 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 will ensure a separation of Concern.

Add Class Library Core to the solution - Samples.AspCoreEF.DAL.EF

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 had two models: Person and Task, we will use the same.

  1. public class Person {  
  2.     public int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public DateTime CreationDate {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public DateTime UpdatedDate {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
  19. public class Task {  
  20.     public string Id {  
  21.         get;  
  22.         set;  
  23.     }  
  24.     public string Title {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public string Description {  
  29.         get;  
  30.         set;  
  31.     }  
  32.     public DateTime CreationTime {  
  33.         get;  
  34.         set;  
  35.     }  
  36.     public TaskState State {  
  37.         get;  
  38.         set;  
  39.     }  
  40.     public virtual Person AssignedTo {  
  41.         get;  
  42.         set;  
  43.     }  
  44.     public DateTime CreationDate {  
  45.         get;  
  46.         set;  
  47.     }  
  48.     public DateTime UpdatedDate {  
  49.         get;  
  50.         set;  
  51.     }  
  52.     public Task() {  
  53.         CreationTime = DateTime.UtcNow;  
  54.         State = TaskState.Open;  
  55.     }  
  56. }  
  57. public enum TaskState: byte {  
  58.     /// <summary>  
  59.     /// The task is Open.  
  60.     /// </summary>  
  61.     Open = 0,  
  62.         /// <summary>  
  63.         /// The task is active.  
  64.         /// </summary>  
  65.         Active = 1,  
  66.         /// <summary>  
  67.         /// The task is completed.  
  68.         /// </summary>  
  69.         Completed = 2,  
  70.         /// <summary>  
  71.         /// The task is closed.  
  72.         /// </summary>  
  73.         Closed = 3  
  74. }  
ASP.NET Core

ASP.NET Core

ASP.NET Core

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:

ASP.NET Core
 
ASP.NET Core

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

ASP.NET Core

Or: Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.0.1

We will 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.

  1. public class TaskSystemDbContext: DbContext {  
  2.     public TaskSystemDbContext(DbContextOptions < TaskSystemDbContext > dbcontextoption): base(dbcontextoption) {}  
  3.     public DbSet < Person > Persons {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     public DbSet < Task > Tasks {  
  8.         get;  
  9.         set;  
  10.     }  
  11. }  
ASP.NET Core

So, we will have this structure,

ASP.NET Core

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.

ASP.NET Core

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. publicvoid ConfigureServices(IServiceCollection services)    
  2. AddMvc();   

We will add this block related to the connection to SQL Server database.

  1. //Using SQL Server   
  2. varsqlconnection = @"Server=(localdb)\v11.0;Database=samplecoreEF;Trusted_Connection=True;";    
  3. 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.

ASP.NET Core

Thus, we will call it in Startup.cs in the given way.

  1. //Using Postgresql  
  2. varconnectionString = Configuration["DbContextSettings:ConnectionString"];  
  3. AddDbContext < TaskSystemDbContext > (opts => opts.UseNpgsql(connectionString));   

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.

ASP.NET Core
  1. [Route("api/persons")]  
  2. public class PersonController: Controller {  
  3.         private TaskSystemDbContext _taskContext;  
  4.         public PersonController(TaskSystemDbContext taskContext) {  
  5.             _taskContext = taskContext;  
  6.         }  
  7.         // GET: api/values  
  8.         [HttpGet]  
  9.         public IEnumerable < string > Get() {  
  10.             //List<Person> list1 = new List<Person>();  
  11.             //foreach (var person in _taskContext.Persons)  
  12.             //    list1.Add(person);  
  13.             //var list = list1.Select(p => p.Name);  
  14.             //return list;  
  15.             var list = _taskContext.Persons.ToList().Select(p => p.Name);  
  16.             return list;  
  17.         }  

Code on github.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now