Entity Framework With .Net Core MVC (4), Code-First

After I wrote several articles on this site, I found out it seemed almost for every article, I needed to set up a sample application associated with an entity framework if accessing the database. And, every time, I needed to rewrite the setup process from scratch in order for a new reader to follow along easily. Even for introducing a very simple concept, such as Caching, I needed to spend 80% of the time setting up the sample app, and only 20%  on introducing the Caching concept itself.
 
Therefore, I think it is better to write a basic model such as entity framework sample for various approaches, and then I can reuse them when needed. I made a list of the series of articles below, I will write them one by one, while the Entity framework overview and concept will be covered in the article (0):
  • Entity Framework (0), Overview
  • Entity Framework (1), with .Net MVC, Code-First
  • Entity Framework (2), with .Net MVC, Database-First
  • Entity Framework (3), with .Net MVC, Model-First
  • Entity Framework (4), with .Net Core MVC, Code-First (this article)
  • Entity Framework (5), with .Net Core MVC, Database-First
  • Entity Framework (6), with .Net Core MVC, Model-First
Note
We write the Entity Framework for MVC module, but the pattern is the same or similar when applying to Web Application or Web API.
 

Introduction

 
This article is about Entity Framework with .Net Core MVC, Code-First approach.  Compared with article (1), Entity Framework with .Net MVC, Code-First, they have a lot of similar features.  We try to emphasize the differences.  However, in order for reader to have a consistent reading, we will keep the similar ones as is.
 
We will make a sample app step by step,
  • Step 1: Create an ASP.NET MVC application
  • Step 2: Add a Model
  • Step 3: Set up DbContext
  • Step 4: Set up Data Connection
  • Step 4.5: Migrate and Update database (this step is not necessary for .Net Framework MVC)
  • Step 5: Create Controller to access data from entity framework
  • Step 6: Run the App and Test
At the end, we will have an .Net Core MVC app that can consume a database directly through entity framework.
 

Step 1 - Create an ASP.NET Core MVC app

 
We use the current version of Visual Studio 2019 16.9.3 and .NET Core 5.0 to build the app:
  • Start Visual Studio and select Create a new project.
  • In the Create a new project dialog, select ASP.NET Core Web App (Model-View-Controller) > Next.
  • In the Configure your new project dialog, enter MvcMovie for Project name > Next.
  • In the Additional Information dialog, select .NET 5.0 in the target framework dropdowns > Create
Note
  1. For biginners, you may reference here.
  2. We use the same project name as article (1), to keep it consistent.
Build and run the app, you will see the following image shows the app,
 
 

Step 2: Add a Data Model

 
Add a data model, an entity class, into the app, with name as Movie:
  • In Solution Explorer, right click the Models folder, > Add,
  • In the Add New item dialog, Select Class, Enter the class name Movie > Add.
  • Add the following five properties to the Movie class:
  1. using System;  
  2.   
  3. namespace MvcMovie.Models  
  4. {  
  5.     public class Movie  
  6.     {  
  7.         public int ID { getset; }  
  8.         public string Title { getset; }  
  9.         public DateTime ReleaseDate { getset; }  
  10.         public string Genre { getset; }  
  11.         public decimal Price { getset; }  
  12.     }  

Step 3: Set up DbContext

 
Add another class for DbContext name as MvcMovieContext (Note: the content is different from one of MVC):
  1. using Microsoft.EntityFrameworkCore;  
  2.   
  3. namespace MvcMovie.Models  
  4. {  
  5.     public partial class MovieCoreDBContext : DbContext  
  6.     {  
  7.         public MovieCoreDBContext()  
  8.         { }  
  9.         public MovieCoreDBContext(DbContextOptions<MovieCoreDBContext> options)  
  10.             : base(options)  
  11.         { }  
  12.         public virtual DbSet<Movie> Movies { getset; }  
  13.     }  

In order to use Microsoft.EntityFrameworkCore, and the related class, you need to install it from NuGet Package Manager.
 

Step 4: Set up Data Connection

 
Add the Connection in the appsettings.json file
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   
  10.   "ConnectionStrings": {  
  11.     "MovieCoreConnection""Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\Movies.mdf",  
  12.   },  
  13.   
  14.   "AllowedHosts""*"  
Register the database connection context into Class starup.cs inside ConfigureServices,
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     services.AddDbContext<MovieCoreDBContext>(options =>  
  4.             options.UseSqlServer(Configuration.GetConnectionString("MvcCoreMovieContext"))); 
  5.     ......

In order to use the middleware UseSqlServeryou need to install Microsoft.EntityFrameworkCore.SqlServer from NuGet Package Manager.
 
Note 
In .Net Framework MVC, you don't actually need to add connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class. However, in .Net Core, you have to add a connection string in the appsettings.json file and have to register it in Startup file.  Otherwise, it will not work.
 
And finally, you even have to Migrate and Update database before to make the database work, see the next step.
 

Step 4.5:  Migrate and Update database (not necessary for .Net Framework MVC)

 
We add the Step 4.5 here to do the extra job. Click "Tools->NuGet Package Manager->Package Manager Console", and run the PMC command (make them in one line),
  1. Add-Migration -Name initialMigration -Context MvcCoreMovieContext 
 
Run PMC command,
  1. update-database 
Note
her stuff from the Step 5 below will be the exactly same procedure as MVC module, we will just keep it for consistence.
 

Step 5:  Create Controller to access data from entity framework

 
From Visual Studio IDE,
  • Right-click the Controllers folder.
  • Select Add > New Scaffolded Item Or Controller to open the window Add New Scaffolded Item
  • In the Add New Scaffold Item dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add.;
  • In the Add Controller dialog box,
    • Select Movie (MvcMovie.Models) for the Model class.
    • Select MovieDBContext (MvcMovie.Models) for the Data context class.
    • For the Controller name enter MoviesController.
    • Click Add.
 
(If you get an error, you probably didn't build the application before starting adding the controller.) Visual Studio creates the following files and folders:
  • A MoviesController.cs file in the Controllers folder.
  • A Views\Movies folder.
  • Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Movies folder
 Visual Studio automatically created the CRUD (create, read, update, and delete) action methods and views:
 
Note
We will not exame the code in details, if you wanted, you may go here.
 

Step 6: Run the App, and Test

 
For convenience, you can update one line code in file Views/Shared/_Layout.chtml 
  1. <body>  
  2.     <div class="navbar navbar-inverse navbar-fixed-top">  
  3.         <div class="container">  
  4.             <div class="navbar-header">  
  5.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" 
  6.                     <span class="icon-bar"></span>  
  7.                     <span class="icon-bar"></span>  
  8.                     <span class="icon-bar"></span>  
  9.                 </button>  
  10.                 @Html.ActionLink("MVC Core Movie""Index""Movies"new { area = "" }, new { @class = "navbar-brand" })  
  11.             </div>  
  12.             <div class="navbar-collapse collapse">  
  13.                 <ul class="nav navbar-nav">  
  14.                     <li>@Html.ActionLink("Home""Index""Home")</li>  
  15.                     <li>@Html.ActionLink("About""About""Home")</li>  
  16.                     <li>@Html.ActionLink("Contact""Contact""Home")</li>  
  17.                 </ul>  
  18.             </div>  
  19.         </div>  
  20.     </div>  
  21.     ......
  22. </body> 
Run the App, the final result will be:

 

Summary

 
The .NET Core MVC module for Code-First approach is very similar to the MVC module, except you
  1. have to add a connection string in the appsettings.json file and 
  2. have to register it in Startup file. 
  3. have to Migrate and Update database, otherwise, it won't work. 
 
Reference