Building An ASP.NET Core Application With Web API And Code First Development

Introduction

In the previous article, we’ve learned the high-level overview of what Entity Framework is all about and learned how to build a web application quickly using Entity Framework’s Database-First development.

This time we will build a simple, yet realistic ASP.NET Core application and showcase the feature of Entity Framework Core. But before we dig down further, let’s take a quick recap about the high-level differences and key benefits of Code-First and Database-First design workflows, then we’ll decide which we are going to use in our project.

Design Workflows

Just so you remember, there are two main design workflows that are supported by Entity Framework Core: The Code-First approach which is you create your classes (POCO Entities) and generate a new database out from it. The Database-First approach allows you to use an existing database and generate classes based on your database schema. The table below shows the high-level process of how each design workflow works.

Code FirstDatabase First
 ASP.NET Core  ASP.NET Core

Figure 1: EF Core Design Workflows

Code First (New Database)
  • Good option if you don't know the whole picture of your database as you can just update your Plain Old Class Object (POCO) entities and let EF sync your changes to your database. In other words, you can easily add or remove features defined in your class without worrying about syncing your database using Migrations.
  • You don't have to worry about your database as EF will handle the creation for you. In essence, the database is just a storage medium with no logic.
  • You will have full control over the code. You simply define and create POCO entities and let EF generate the corresponding Database for you. The downside is if you change something in your database manually, you will probably lose them because your code defines the database.
  • It's easy to modify and maintain as there will be no autogenerated code.
Database First (Existing Database)
  • A good option if you are good at the database or you have a database designed by DBAs, or you already have an existing database developed.
  • You don't have to worry about creating POCO objects as EF will generate them for you based on your existing database.
  • You can create partial classes if you want additional features in POCO entities.
  • You can manually modify your database because the database defines your POCO entities (domain model).
  • Provides more flexibility and control over database configuration.
Wrapping Up

You may go for the database-first route when you have an existing database developed separately or when the time is important for you. Database first enables us to build apps faster as you can just generate your domain models in just a few clicks. For larger applications or for long-term client projects, code first provides us the control we need to create the most efficient program and also gives us the protection and consistency of a versioned controlled database while reducing bloat.

Keep in mind that both design workflows have its advantages. Choosing which approach to use is very important decision to make when you start a new project, so be sure to know what your project requires and expect.

The table below outlines my own personal recommendation as to which design workflow to consider when building an application.

 Database FirstCode First
Code GenerationCreate the database schema using your preferred tools (e.g SQL Server Management Studio) and import that database and schema using a script to scaffold everything for you.Write classes with properties you want to keep track of and then define relationships between other classes.
Syncing ChangesCreate a migration that represents the changes and runs the script against the database.You create the migrations when you need them, and the code will use those files (and a corresponding table in the target database) to keep the schema changes in sync with what the code expects. In other words, you can manage your database schema without ever writing any SQL.
Type of project best suited forIt makes more sense to use database-first for existing project since you don’t need to make big changes to scale the database.  You could also use this approach for new projects when a database is developed separately by DBA’s and owned by another team.Code-first makes more sense if you're developing a new application from scratch as you can grow and evolve your model as you develop.

Taking a Choice

As we can easily see by judging the differences between the two approaches, there is no such thing as an overall better or best approach: conversely, we could say that each project scenario will likely have a most suitable approach.

Now with regards to the application that we are going to build, considering the fact we don’t have a database yet and we’re aiming for a flexible, mutable small-scale data structure, adopting the Code-First approach would probably be a good choice. That’s what we’re going to do, build an ASP.NET Core application from scratch using Entity Framework Core's Code-First approach.

The ASP.NET Core Revolution

To summarize what happened in the ASP.NET world within the last year is not an easy task: in short words, we could say that we’re undoubtedly facing the most important series of changes in the .NET Framework since the year it came to life. ASP.NET Core is a complete re-implementation of ASP.NET which unites all the previous web application technologies such as MVC, Web API and Razor Pages into a single programming module, formerly known as MVC6. The new framework introduces a fully-featured cross-platform component, also known as .NET Core, shipped with a brand-new open-source .NET Compiler Platform (currently known as Roslyn), a cross-platform runtime known as CoreCLR.

ASP.NET Core is a new open-source and cross-platform framework for building modern cloud-based web apps It has been built from the ground up to provide an optimized development framework for web apps that are either deployed to the cloud or in your local servers. Adding to that, it was redesigned to make ASP.NET leaner, modular (so you can just add features that your application requires), cross-platform (so you can easily develop and run your app on Windows, Mac or Linux that is pretty awesome) and cloud-optimized (so you can deploy and debug apps over the cloud).

Three Players, One Goal

Our main goal is to build a data-driven web application using the three cutting-edge technologies: ASP.NET Core MVC, Web API, and Entity Framework Core.

ASP.NET Web API is a framework used to build HTTP services and is an ideal platform for building RESTful applications on the .NET Framework.

ASP.NET Core MVC is a pattern-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup or HTML.

We will use ASP.NET Core to build  REST API's (Web API) and as our front-end framework (MVC) to generate pages or views (a.k.a User Interface). On the other hand, we will be using Entity Framework Core as our data access mechanism to work with data from the database. The figure below illustrates how each technology interacts with each other.

ASP.NET Core
Figure 2: High-level process flow

The figure above illustrates how the process works when a user accesses an information from the database. When a user requests a page, it will bring up the View/UI (MVC). When a user wants to view some data, MVC app will then talk to the Web API service to process it. Web API will then talk to EF Core to handle the actual request (CRUD operations) and then updates the database when necessary.

Setting Up an ASP.NET Core Web API Project

Now that we already know the high-level overview of ASP.NET Core and EF Core, it’s time for us to get our hands dirty by building a simple, yet data-driven web application using ASP.NET Core with Entity Framework Core. Let’s create the Web API project first.

Fire-up Visual Studio 2017 and let’s create a new ASP.NET Core Web Application project. To do this, select File > New > Project. In the New Project dialog select Visual C# > Web > ASP.NET Core Web Application (.NET Core) just like in the figure below,

ASP.NET Core
Figure 3: Create New ASP.NET Core Project 

In the dialog, enter the name of your project and then click the OK button to proceed to the next step. Note that for this specific demo we named the project as "StudentApplication.API". Now click on Web API template as shown in the figure below.

ASP.NET Core
Figure 4: ASP.NET Core Web API Template

With the new ASP.NET Core project template dialog, you can now choose to use ASP.NET Core 1.0 or 1.1 using the combo-box at the top of the screen. The default template as of this time of writing is ASP.NET Core 1.1. Additionally, you can choose to add Container support to your project with the checkbox at the bottom-left of the screen.  This option adds:

  • Docker files to your project for building Container images
  • a Docker Compose project to define how you instance your Containers
  • Multi-project/container debugging support for Containers

For the simplicity of this exercise, let’s just omit the use of containers.

Now click again the OK button to let Visual Studio generate the default files for you. The figure below shows the generated files,

ASP.NET Core
Figure 5: Visual Studio Default Generated Files

Let’s take a quick overview of each file generated.

If you already know the core significant changes of ASP.NET Core then you may skip this part, but if you are new to ASP.NET Core then I would like to highlight some of those changes. If you have worked with previous versions of ASP.NET before then you will notice that the new project structure is totally different. The project now includes these files:

  • Connected Services - allow service providers to create Visual Studio extensions that can be added to a project without leaving the IDE. It also allows you to connect your ASP.NET Core Application or Mobile Services to Azure Storage services. Connected Services takes care of all the references and connection code, and modifies your configuration files accordingly
  • Controllers - this is where you put all your Web API or MVC controller classes. Note that the Web API project will by default generate the ValuesController.cs file.
  • wwwroot - is a folder in which all your static files will be placed. These are the assets that the web app will serve directly to the clients, including HTML, CSS, Image and JavaScript files.
  • json - contains application settings.
  • cs - this is where you put your startup and configuration code.
  • cs - this is where you initialize all services needed for your application.
Running the Project for the First Time

To ensure that we got everything we need for our Web API project, let’s try to build and run the project.  We can do this by pressing the CTRL + F5 keys. This will compile, build and automatically launches the browser window. If you are getting the following result below, then we can safely assume that our project is good to go.

ASP.NET Core
Figure 6: Initial Run

Setting Up Entity Framework Core

Let’s install Entity Framework Core packages into our project. Go to Tools > NuGet Package Manager -> Package Manager Console and run the following command individually:

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools

After successfully installing the packages above, make sure to check your project references to ensure that we got them in the project. See the figure below.

ASP.NET Core
Figure 7: Entity Framework Core Package References

These packages are used to provide Entity Framework Core migration. Migration enables us to generate database, sync and update tables based on our Entity.

Creating the Model

We will start by creating the “Models” folder within the root of the application. Add a new class file to the Models folder and name it as “Student.cs”, then replace the default generated code with the following,

  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3. using System.ComponentModel.DataAnnotations.Schema;  
  4.   
  5. namespace StudentApplication.API.Models  
  6. {  
  7.     public class Student  
  8.     {  
  9.         [Key]  
  10.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  11.         public long StudentId { get; set; }  
  12.         public string FirstName { get; set; }  
  13.         public string LastName { get; set; }  
  14.         public string Gender { get; set; }  
  15.         public DateTime? DateOfBirth { get; set; }  
  16.         public DateTime? DateOfRegistration { get; set; }  
  17.         public string PhoneNumber { get; set; }  
  18.         public string Email { get; set; }  
  19.         public string Address1 { get; set; }  
  20.         public string Address2 { get; set; }  
  21.         public string City { get; set; }  
  22.         public string State { get; set; }  
  23.         public string Zip { get; set; }  
  24.     }  
  25. }  

The code above is nothing but just a simple class that houses some properties. You may have noticed that we decorated the StudentId property with Key and DatabaseGenerated attributes. This is because we will be converting this class into a database table and the StundentId will serve as our primary key with auto-incremented identity. These attributes resides within System.ComponentModel.DataAnnotations. For more details about Data Annotations see:  Using Data Annotations for Model Validation

Creating an Empty Database

Now it's time for us to create our database. Open SQL Express Management Studio and then execute the following command:

CREATE DATABASE StundentApplication

The command above should create a blank database in your local.

Defining a DBContext

Entity Framework Core Code-First development approach requires us to create a data access context class that inherits from the DbContext class. Now, let's add a new class to the Models folder. Name the class as "ApplicationContext" and then copy the following code below,

  1. using Microsoft.EntityFrameworkCore;  
  2.   
  3. namespace StudentApplication.API.Models  
  4. {  
  5.     public class ApplicationContext: DbContext  
  6.     {  
  7.         public ApplicationContext(DbContextOptions opts) : base(opts)  
  8.         {  
  9.         }  
  10.   
  11.         public DbSet<Student> Students { get; set; }  
  12.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  13.         {  
  14.         }  
  15.     }  
  16. }  

The code above defines a context and an entity class that makes up our model. A DbContext must have an instance of DbContextOptions in order to execute. This can be configured by overriding OnConfiguring, or supplied externally via a constructor argument. In our example above, we opt to choose constructor argument for configuring our DbContext.

Registering the DbContext with Dependency Injection

Our ApplicationContext class will act as a service. This service will be registered with Dependency Injection(DI) during application startup. This would enable our API Controller or other services gain access to the ApplicationContext via constructor parameters or properties.

In order for other services to make use of ApplicationContext, we will register it as a service. To enable the service, do following steps,

  1. Define the following database connection string under appsettings.jsonfile,
    1. "ConnectionString": {  
    2.   "StudentApplicationDB""Server=SSAI-L0028-HP\\SQLEXPRESS;Database=StundentApplication;Trusted_Connection=True;"  
    3. }  
  1. Open Startup.csand declare the following namespace references
    1. using Microsoft.EntityFrameworkCore;  
    2. using StudentApplication.API.Models;  
    3. using StudentApplication.API.Models.DataManager;  
    4. using StudentApplication.API.Models.Repository  
  1. Add the following code within ConfigureServicesmethod to register our ApplicationContext as a service
    1. public void ConfigureServices(IServiceCollection services)  
    2. {  
    3.      // Add framework services.  
    4.      services.AddDbContext<ApplicationContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:StudentApplicationDB"]));  
    5.      services.AddMvc();  
    6. }  
Adding Migrations

Our next step is to add Code-First Migrations. Migrations automate the creation of database based on our Model. Run the following command in the PM console:

PM> Add-Migration StudentApplication.API.Models.ApplicationContext

When the command is executed successfully, it should generate the migration files as shown in the figure below,

ASP.NET Core
Figure 8: Generated EF Migration Files

Now, switch back to the Package Manager Console and run the following command:

PM> update-database

The command above should generate the database table based on our Entity. Here’s the sample screenshot of the generated database table,

ASP.NET Core
Figure 9: Generated Table

Implementing a Simple Data Repository

We don't want our API Controller to access directly our ApplicationContext service, instead, we will let other services handle the communication between our ApplicationContext and API Controller. Having said that, we are going to implement a basic generic repository for handling data access within our application. Add a new folder under Models and name it as “Repository”. Create a new interface and name it as “IDataRepository”. Update the code within that file so it would look similar to the following code below,

  1. using System.Collections.Generic;  
  2.   
  3. namespace StudentApplication.API.Models.Repository  
  4. {  
  5.     public interface IDataRepository<TEntity, U> where TEntity : class  
  6.     {  
  7.         IEnumerable<TEntity> GetAll();  
  8.         TEntity Get(U id);  
  9.         long Add(TEntity b);  
  10.         long Update(U id, TEntity b);  
  11.         long Delete(U id);  
  12.     }  
  13.   
  14. }  

The code above defines our IDataRepository interface. An interface is just a skeleton of a method without the actual implementation. This interface will be injected into our API Controller so we will only need to talk to the interface rather than the actual implementation of our repository. One of the main benefits of using the interface is to make our code reusable and easy to maintain.

Creating the DataManager

Next is we are going to create a concrete class that implements the IDataRepository interface. Add a new folder under Models and name it as “DataManager”. Create a new class and name it as “StudentManager”. Update the code within that file so it would look similar to the following code below,

  1. using StudentApplication.API.Models.Repository;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace StudentApplication.API.Models.DataManager  
  6. {  
  7.     public class StudentManager : IDataRepository<Student, long>  
  8.     {  
  9.         ApplicationContext ctx;  
  10.         public StudentManager(ApplicationContext c)  
  11.         {  
  12.             ctx = c;  
  13.         }  
  14.   
  15.         public Student Get(long id)  
  16.         {  
  17.             var student = ctx.Students.FirstOrDefault(b => b.StudentId == id);  
  18.             return student;  
  19.         }  
  20.   
  21.         public IEnumerable<Student> GetAll()  
  22.         {  
  23.             var students = ctx.Students.ToList();  
  24.             return students;  
  25.         }  
  26.   
  27.         public long Add(Student stundent)  
  28.         {  
  29.             ctx.Students.Add(stundent);  
  30.             long studentID = ctx.SaveChanges();  
  31.             return studentID;  
  32.         }  
  33.   
  34.         public long Delete(long id)  
  35.         {  
  36.             int studentID = 0;  
  37.             var student = ctx.Students.FirstOrDefault(b => b.StudentId == id);  
  38.             if (student != null)  
  39.             {  
  40.                 ctx.Students.Remove(student);  
  41.                 studentID = ctx.SaveChanges();  
  42.             }  
  43.             return studentID;  
  44.         }  
  45.   
  46.         public long Update(long id, Student item)  
  47.         {  
  48.             long studentID  = 0;  
  49.             var student = ctx.Students.Find(id);  
  50.             if (student != null)  
  51.             {  
  52.                 student.FirstName = item.FirstName;  
  53.                 student.LastName = item.LastName;  
  54.                 student.Gender = item.Gender;  
  55.                 student.PhoneNumber = item.PhoneNumber;  
  56.                 student.Email = item.Email;  
  57.                 student.DateOfBirth = item.DateOfBirth;  
  58.                 student.DateOfRegistration = item.DateOfRegistration;  
  59.                 student.Address1 = item.Address1;  
  60.                 student.Address2 = item.Address2;  
  61.                 student.City = item.City;  
  62.                 student.State = item.State;  
  63.                 student.Zip = item.Zip;  
  64.   
  65.                 studentID = ctx.SaveChanges();  
  66.             }  
  67.             return studentID;  
  68.         }  
  69.     }  
  70. }  

The DataManager class handles all database operations for our application. The purpose of this class is to separate the actual data operation logic from our API Controller, and to have a central class for handling create, update, fetch and delete (CRUD) operations.

At the moment, the DataManager class contains five methods: The Get() method gets a specific student record from the database by passing an Id. It uses a LINQ syntax to query the data and returns a Student object. The GetAll() method gets all students records from the database as you could probably guess based on the method name. The Add() method creates a new student record in the database. The Delete() method removes a specific student record from the database based on the Id. Finally, the Update() method updates a specific student record in the database. All methods above use LINQ to query the data from the database.

Creating an API Controller

Now that our DataManager is all set, it's time for us to create the API Controller and expose some endpoints for handling CRUD operations. 

Go ahead and right click on the Controllers folder and then select Add > New Item > Web API Controller class. Name the class as "StudentController" just like in the figure below and then click Add.

ASP.NET Core
Figure 10: New Web API Controller Class

Now replace the default generated code so it would look similar to the following code below,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using StudentApplication.API.Models;  
  7. using StudentApplication.API.Models.Repository;  
  8. using StudentApplication.API.Models.DataManager;  
  9.   
  10.   
  11. namespace StudentApplication.API.Controllers  
  12. {  
  13.     [Route("api/[controller]")]  
  14.     public class StudentController : Controller  
  15.     {  
  16.         private IDataRepository<Student,long> _iRepo;   
  17.         public StudentController(IDataRepository<Student, long> repo)  
  18.         {  
  19.             _iRepo = repo;  
  20.         }  
  21.   
  22.         // GET: api/values  
  23.         [HttpGet]  
  24.         public IEnumerable<Student> Get()  
  25.         {  
  26.             return _iRepo.GetAll();  
  27.         }  
  28.   
  29.         // GET api/values/5  
  30.         [HttpGet("{id}")]  
  31.         public Student Get(int id)  
  32.         {  
  33.             return _iRepo.Get(id);  
  34.         }  
  35.   
  36.         // POST api/values  
  37.         [HttpPost]  
  38.         public void Post([FromBody]Student student)  
  39.         {  
  40.             _iRepo.Add(student);  
  41.         }  
  42.   
  43.         // POST api/values  
  44.         [HttpPut]  
  45.         public void Put([FromBody]Student student)  
  46.         {  
  47.             _iRepo.Update(student.StudentId,student);  
  48.         }  
  49.   
  50.         // DELETE api/values/5  
  51.         [HttpDelete("{id}")]  
  52.         public long Delete(int id)  
  53.         {  
  54.             return _iRepo.Delete(id);  
  55.         }  
  56.     }  
  57. }  

The StudentController derives from the Controller base and by decorating it with the Route attribute enables this class to become a Web API Controller.

If you notice, we have used Controller Injection to subscribed to the IDataRepository interface. So instead of taking directly to the StudentManager class, we just simply talk to the interface and make use of the methods that are available.

The StudentController has five (5) main methods/endpoints. The first Get() method class the GetAll() method from IDataRepository interface and basically returns all the list of Student from the database. The second Get() method returns a specific Student object based on the Id. Notice that the second Get() method is decorated with [HttpGet("{id}")], which means append the "id" to the route template. The "{id}" is a placeholder variable for the ID of the Student object. When the second Get() method is invoked, it assigns the value of "{id}" in the URL to the method's id parameter. The Post() method adds a new record to the database. The Put() method updates a specific record from the database. Notice that both Post() and Put() uses a [FromBody] tag. When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. Finally, the Delete() method removes a specific record from the database.

Creating an ASP.NET Core MVC Application

At this point, we already have all the requirement we need to build the UI part of this demo. First we created the database, set up our data access using Entity Framework Core Code-First and finally, we already have our Web API ready. Now it's time for us to create a web application that consumes our Web API endpoints.

Now go ahead and create a new ASP.NET Core project. Right click on the Solution and then select Add > New Project > ASP.NET Core Web Application (.NET Core). You should be able to see something like this,

ASP.NET Core
Figure 11: New ASP.NET Core Web Application Project

To be more consistent, name the project as "StudentApplication.Web" and then click OK. In the next dialog, select "Web Application" under ASP.NET Core 1.1 templates and then click OK to let Visual Studio generate the default files for us.

Integrating Newtonsoft.Json

Let's continue by installing Newtonsoft.Json package in the project. Right click on the project and then select Manage Nuget Packages. In the browse tab, type in "NewtonSoft" and it should result to something like this,

ASP.NET Core
Figure 12: Nuget

Click "install" to add the lastest package version to the project.

We will be using Newtonsoft.Json later in our code to serialize and deserialize object from an API request.

The Helper Class

Create a new class at the root of the application and name it as "Helper.cs" and then copy the following code below,

  1. using System;  
  2. using System.Net.Http;  
  3. using System.Net.Http.Headers;  
  4.   
  5. namespace StudentApplication.Web.Helper  
  6. {  
  7.   
  8.     public class StudentAPI  
  9.     {  
  10.         private string _apiBaseURI = "http://localhost:60883";  
  11.         public HttpClient InitializeClient()  
  12.         {  
  13.             var client = new HttpClient();  
  14.             //Passing service base url    
  15.             client.BaseAddress = new Uri(_apiBaseURI);  
  16.   
  17.             client.DefaultRequestHeaders.Clear();  
  18.             //Define request data format    
  19.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  20.   
  21.             return client;  
  22.         }  
  23.     }  
  24.   
  25.     public class StudentDTO  
  26.     {  
  27.         public long StudentId { get; set; }  
  28.         public string FirstName { get; set; }  
  29.         public string LastName { get; set; }  
  30.         public string Gender { get; set; }  
  31.         public DateTime? DateOfBirth { get; set; }  
  32.         public DateTime? DateOfRegistration { get; set; }  
  33.         public string PhoneNumber { get; set; }  
  34.         public string Email { get; set; }  
  35.         public string Address1 { get; set; }  
  36.         public string Address2 { get; set; }  
  37.         public string City { get; set; }  
  38.         public string State { get; set; }  
  39.         public string Zip { get; set; }  
  40.     }  
  41. }  

The Helper.cs file contains two (2) main classes: The StudentAPI and StudentDTO. The StudentAPI class has a method InitializeClient() to initialize and HttpClient object. We will be needing this method later to access the API endpoints. The StudentDTO is nothing but a plain class that mimics the Student class from our API Controller. We will be using this class as object parameter for API request.

Note: When testing this in your local, you must change the value in the _apiBaseURI variable to where your Web API project is hosted, or if you are running locally using IISExpress then change the value of the port number generated by Visual Studio.

The Controller

Add a new controller under the Controllers folder and name it as "StudentsController". Replace the default generated code with the following code below,

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Newtonsoft.Json;  
  3. using StudentApplication.Web.Helper;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Net.Http;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace StudentApplication.Web.Controllers  
  11. {  
  12.     public class StudentsController : Controller  
  13.     {  
  14.         StudentAPI _studentAPI = new StudentAPI();  
  15.   
  16.         public async Task<IActionResult> Index()  
  17.         {  
  18.             List<StudentDTO> dto = new List<StudentDTO>();  
  19.   
  20.             HttpClient client = _studentAPI.InitializeClient();  
  21.   
  22.             HttpResponseMessage res = await client.GetAsync("api/student");  
  23.   
  24.             //Checking the response is successful or not which is sent using HttpClient    
  25.             if (res.IsSuccessStatusCode)  
  26.             {  
  27.                 //Storing the response details recieved from web api     
  28.                 var result = res.Content.ReadAsStringAsync().Result;  
  29.   
  30.                 //Deserializing the response recieved from web api and storing into the Employee list    
  31.                 dto = JsonConvert.DeserializeObject<List<StudentDTO>>(result);  
  32.   
  33.             }  
  34.             //returning the employee list to view    
  35.             return View(dto);  
  36.         }  
  37.   
  38.         // GET: Students/Create  
  39.         public IActionResult Create()  
  40.         {  
  41.             return View();  
  42.         }  
  43.   
  44.         // POST: Students/Create  
  45.         [HttpPost]  
  46.         [ValidateAntiForgeryToken]  
  47.         public IActionResult Create([Bind("StudentId,FirstName,LastName,Gender,DateOfBirth,DateOfRegistration,PhoneNumber,Email,Address1,Address2,City,State,Zip")] StudentDTO student)  
  48.         {  
  49.             if (ModelState.IsValid)  
  50.             {  
  51.                 HttpClient client = _studentAPI.InitializeClient();  
  52.   
  53.                 var content = new StringContent(JsonConvert.SerializeObject(student), Encoding.UTF8,"application/json");  
  54.                 HttpResponseMessage res = client.PostAsync("api/student", content).Result;  
  55.                 if (res.IsSuccessStatusCode)  
  56.                 {  
  57.                     return RedirectToAction("Index");  
  58.                 }  
  59.             }  
  60.             return View(student);  
  61.         }  
  62.   
  63.         // GET: Students/Edit/1  
  64.         public async Task<IActionResult> Edit(long? id)  
  65.         {  
  66.             if (id == null)  
  67.             {  
  68.                 return NotFound();  
  69.             }  
  70.   
  71.             List<StudentDTO> dto = new List<StudentDTO>();  
  72.             HttpClient client = _studentAPI.InitializeClient();  
  73.             HttpResponseMessage res = await client.GetAsync("api/student");  
  74.    
  75.             if (res.IsSuccessStatusCode)  
  76.             {   
  77.                 var result = res.Content.ReadAsStringAsync().Result;  
  78.                 dto = JsonConvert.DeserializeObject<List<StudentDTO>>(result);  
  79.             }  
  80.   
  81.             var student = dto.SingleOrDefault(m => m.StudentId == id);  
  82.             if (student == null)  
  83.             {  
  84.                 return NotFound();  
  85.             }  
  86.   
  87.             return View(student);  
  88.         }  
  89.   
  90.         // POST: Students/Edit/1  
  91.         [HttpPost]  
  92.         [ValidateAntiForgeryToken]  
  93.         public IActionResult Edit(long id, [Bind("StudentId,FirstName,LastName,Gender,DateOfBirth,DateOfRegistration,PhoneNumber,Email,Address1,Address2,City,State,Zip")] StudentDTO student)  
  94.         {  
  95.             if (id != student.StudentId)  
  96.             {  
  97.                 return NotFound();  
  98.             }  
  99.   
  100.             if (ModelState.IsValid)  
  101.             {  
  102.                 HttpClient client = _studentAPI.InitializeClient();  
  103.   
  104.                 var content = new StringContent(JsonConvert.SerializeObject(student), Encoding.UTF8, "application/json");  
  105.                 HttpResponseMessage res = client.PutAsync("api/student", content).Result;  
  106.                 if (res.IsSuccessStatusCode)  
  107.                 {  
  108.                     return RedirectToAction("Index");  
  109.                 }  
  110.             }  
  111.             return View(student);  
  112.         }  
  113.   
  114.         // GET: Students/Delete/1  
  115.         public async Task<IActionResult> Delete(long? id)  
  116.         {  
  117.             if (id == null)  
  118.             {  
  119.                 return NotFound();  
  120.             }  
  121.   
  122.             List<StudentDTO> dto = new List<StudentDTO>();  
  123.             HttpClient client = _studentAPI.InitializeClient();  
  124.             HttpResponseMessage res = await client.GetAsync("api/student");  
  125.   
  126.             if (res.IsSuccessStatusCode)  
  127.             {    
  128.                 var result = res.Content.ReadAsStringAsync().Result;   
  129.                 dto = JsonConvert.DeserializeObject<List<StudentDTO>>(result);  
  130.             }  
  131.   
  132.             var student = dto.SingleOrDefault(m => m.StudentId == id);  
  133.             if (student == null)  
  134.             {  
  135.                 return NotFound();  
  136.             }  
  137.   
  138.             return View(student);  
  139.         }  
  140.   
  141.         // POST: Students/Delete/5  
  142.         [HttpPost, ActionName("Delete")]  
  143.         [ValidateAntiForgeryToken]  
  144.         public IActionResult DeleteConfirmed(long id)  
  145.         {  
  146.             HttpClient client = _studentAPI.InitializeClient();  
  147.             HttpResponseMessage res = client.DeleteAsync($"api/student/{id}").Result;  
  148.             if (res.IsSuccessStatusCode)  
  149.             {  
  150.                 return RedirectToAction("Index");  
  151.             }  
  152.   
  153.             return NotFound();  
  154.         }  
  155.   
  156.     }     
  157. }  

Let's see what we just did above.

Notice that our MVC Controller uses an HttpClient object to access our Web API endpoints. We also use the Newtonsoft's JsonConvert.SerializeObject() and JsonConvert.DeserializeObject() to serialize and deserialize the data back and forth.

The Index() action method gets all Student records from the database. This method is defined as asynchronous which returns the corresponding Index View along with the list of Students entity.

The Create() action method simply returns it's corresponding View. The overload Create() action method is decorated with the [HttpPost] attribute which signifies that the method can only be invoked for POST requests. This method is where we actually handle the adding of new data to database if the model state is valid on posts.

The Edit() action method takes an id as the parameter. If the id is null, it returns NotFound(), otherwise it returns the corresponding data to the View. The overload Edit() action method updates the corresponding record to the database based on the id.

Just like the other action, the Delete() action method takes an id as the parameter. If the id is null, it returns NotFound(), otherwise it returns the corresponding data to the View. The overload Delete() action method deletes the corresponding record to the database based on the id.

The Views

The following are the corresponding markup for Index, Create, Edit and Delete Views.

Index

  1. @model IEnumerable<StudentApplication.Web.Helper.StudentDTO>  
  2.   
  3.     @{  
  4.         ViewData["Title"] = "Index";  
  5.         Layout = "~/Views/Shared/_Layout.cshtml";  
  6.     }  
  7.   
  8.     <strong>Index</strong>  
  9.   
  10.     <p>  
  11.         <a asp-action="Create">Create New</a>  
  12.     </p>  
  13.     <table class="table">  
  14.         <thead>  
  15.             <tr>  
  16.                 <th>  
  17.                     @Html.DisplayNameFor(model => model.FirstName)  
  18.                 </th>  
  19.                 <th>  
  20.                     @Html.DisplayNameFor(model => model.LastName)  
  21.                 </th>  
  22.                 <th>  
  23.                     @Html.DisplayNameFor(model => model.Gender)  
  24.                 </th>  
  25.                 <th>  
  26.                     @Html.DisplayNameFor(model => model.DateOfBirth)  
  27.                 </th>  
  28.                 <th>  
  29.                     @Html.DisplayNameFor(model => model.DateOfRegistration)  
  30.                 </th>  
  31.                 <th>  
  32.                     @Html.DisplayNameFor(model => model.PhoneNumber)  
  33.                 </th>  
  34.                 <th>  
  35.                     @Html.DisplayNameFor(model => model.Email)  
  36.                 </th>  
  37.                 <th>  
  38.                     @Html.DisplayNameFor(model => model.Address1)  
  39.                 </th>  
  40.                 <th>  
  41.                     @Html.DisplayNameFor(model => model.Address2)  
  42.                 </th>  
  43.                 <th>  
  44.                     @Html.DisplayNameFor(model => model.City)  
  45.                 </th>  
  46.                 <th>  
  47.                     @Html.DisplayNameFor(model => model.State)  
  48.                 </th>  
  49.                 <th>  
  50.                     @Html.DisplayNameFor(model => model.Zip)  
  51.                 </th>  
  52.                 <th></th>  
  53.             </tr>  
  54.         </thead>  
  55.         <tbody>  
  56.             @foreach (var item in Model)  
  57.             {  
  58.                 <tr>  
  59.                     <td>  
  60.                         @Html.DisplayFor(modelItem => item.FirstName)  
  61.                     </td>  
  62.                     <td>  
  63.                         @Html.DisplayFor(modelItem => item.LastName)  
  64.                     </td>  
  65.                     <td>  
  66.                         @Html.DisplayFor(modelItem => item.Gender)  
  67.                     </td>  
  68.                     <td>  
  69.                         @Html.DisplayFor(modelItem => item.DateOfBirth)  
  70.                     </td>  
  71.                     <td>  
  72.                         @Html.DisplayFor(modelItem => item.DateOfRegistration)  
  73.                     </td>  
  74.                     <td>  
  75.                         @Html.DisplayFor(modelItem => item.PhoneNumber)  
  76.                     </td>  
  77.                     <td>  
  78.                         @Html.DisplayFor(modelItem => item.Email)  
  79.                     </td>  
  80.                     <td>  
  81.                         @Html.DisplayFor(modelItem => item.Address1)  
  82.                     </td>  
  83.                     <td>  
  84.                         @Html.DisplayFor(modelItem => item.Address2)  
  85.                     </td>  
  86.                     <td>  
  87.                         @Html.DisplayFor(modelItem => item.City)  
  88.                     </td>  
  89.                     <td>  
  90.                         @Html.DisplayFor(modelItem => item.State)  
  91.                     </td>  
  92.                     <td>  
  93.                         @Html.DisplayFor(modelItem => item.Zip)  
  94.                     </td>  
  95.                     <td>  
  96.                         <a asp-action="Edit" asp-route-id="@item.StudentId">Edit</a> |  
  97.                         <a asp-action="Details" asp-route-id="@item.StudentId">Details</a> |  
  98.                         <a asp-action="Delete" asp-route-id="@item.StudentId">Delete</a>  
  99.                     </td>  
  100.                 </tr>  
  101.             }  
  102.         </tbody>  
  103.     </table>  

Create

  1. @model StudentApplication.Web.Helper.StudentDTO  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Create";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <strong>Create</strong>  
  9.   
  10. <form asp-action="Create">  
  11.     <div class="form-horizontal">  
  12.         <strong>Student</strong>  
  13.         <hr />  
  14.         <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  15.         <div class="form-group">  
  16.             <label asp-for="FirstName" class="col-md-2 control-label"></label>  
  17.             <div class="col-md-10">  
  18.                 <input asp-for="FirstName" class="form-control" />  
  19.                 <span asp-validation-for="FirstName" class="text-danger"></span>  
  20.             </div>  
  21.         </div>  
  22.         <div class="form-group">  
  23.             <label asp-for="LastName" class="col-md-2 control-label"></label>  
  24.             <div class="col-md-10">  
  25.                 <input asp-for="LastName" class="form-control" />  
  26.                 <span asp-validation-for="LastName" class="text-danger"></span>  
  27.             </div>  
  28.         </div>  
  29.         <div class="form-group">  
  30.             <label asp-for="Gender" class="col-md-2 control-label"></label>  
  31.             <div class="col-md-10">  
  32.                 <input asp-for="Gender" class="form-control" />  
  33.                 <span asp-validation-for="Gender" class="text-danger"></span>  
  34.             </div>  
  35.         </div>  
  36.         <div class="form-group">  
  37.             <label asp-for="DateOfBirth" class="col-md-2 control-label"></label>  
  38.             <div class="col-md-10">  
  39.                 <input asp-for="DateOfBirth" class="form-control" />  
  40.                 <span asp-validation-for="DateOfBirth" class="text-danger"></span>  
  41.             </div>  
  42.         </div>  
  43.         <div class="form-group">  
  44.             <label asp-for="DateOfRegistration" class="col-md-2 control-label"></label>  
  45.             <div class="col-md-10">  
  46.                 <input asp-for="DateOfRegistration" class="form-control" />  
  47.                 <span asp-validation-for="DateOfRegistration" class="text-danger"></span>  
  48.             </div>  
  49.         </div>  
  50.         <div class="form-group">  
  51.             <label asp-for="PhoneNumber" class="col-md-2 control-label"></label>  
  52.             <div class="col-md-10">  
  53.                 <input asp-for="PhoneNumber" class="form-control" />  
  54.                 <span asp-validation-for="PhoneNumber" class="text-danger"></span>  
  55.             </div>  
  56.         </div>  
  57.         <div class="form-group">  
  58.             <label asp-for="Email" class="col-md-2 control-label"></label>  
  59.             <div class="col-md-10">  
  60.                 <input asp-for="Email" class="form-control" />  
  61.                 <span asp-validation-for="Email" class="text-danger"></span>  
  62.             </div>  
  63.         </div>  
  64.         <div class="form-group">  
  65.             <label asp-for="Address1" class="col-md-2 control-label"></label>  
  66.             <div class="col-md-10">  
  67.                 <input asp-for="Address1" class="form-control" />  
  68.                 <span asp-validation-for="Address1" class="text-danger"></span>  
  69.             </div>  
  70.         </div>  
  71.         <div class="form-group">  
  72.             <label asp-for="Address2" class="col-md-2 control-label"></label>  
  73.             <div class="col-md-10">  
  74.                 <input asp-for="Address2" class="form-control" />  
  75.                 <span asp-validation-for="Address2" class="text-danger"></span>  
  76.             </div>  
  77.         </div>  
  78.         <div class="form-group">  
  79.             <label asp-for="City" class="col-md-2 control-label"></label>  
  80.             <div class="col-md-10">  
  81.                 <input asp-for="City" class="form-control" />  
  82.                 <span asp-validation-for="City" class="text-danger"></span>  
  83.             </div>  
  84.         </div>  
  85.         <div class="form-group">  
  86.             <label asp-for="State" class="col-md-2 control-label"></label>  
  87.             <div class="col-md-10">  
  88.                 <input asp-for="State" class="form-control" />  
  89.                 <span asp-validation-for="State" class="text-danger"></span>  
  90.             </div>  
  91.         </div>  
  92.         <div class="form-group">  
  93.             <label asp-for="Zip" class="col-md-2 control-label"></label>  
  94.             <div class="col-md-10">  
  95.                 <input asp-for="Zip" class="form-control" />  
  96.                 <span asp-validation-for="Zip" class="text-danger"></span>  
  97.             </div>  
  98.         </div>  
  99.         <div class="form-group">  
  100.             <div class="col-md-offset-2 col-md-10">  
  101.                 <input type="submit" value="Create" class="btn btn-default" />  
  102.             </div>  
  103.         </div>  
  104.     </div>  
  105. </form>  
  106.   
  107. <div>  
  108.     <a asp-action="Index">Back to List</a>  
  109. </div>  
  110.   
  111. @section Scripts {  
  112.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  113. }  

Edit

  1. @model StudentApplication.Web.Helper.StudentDTO  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Edit";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <strong>Edit</strong>  
  9.   
  10. <form asp-action="Edit">  
  11.     <div class="form-horizontal">  
  12.         <strong>Student</strong>  
  13.         <hr />  
  14.         <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  15.         <input type="hidden" asp-for="StudentId" />  
  16.         <div class="form-group">  
  17.             <label asp-for="FirstName" class="col-md-2 control-label"></label>  
  18.             <div class="col-md-10">  
  19.                 <input asp-for="FirstName" class="form-control" />  
  20.                 <span asp-validation-for="FirstName" class="text-danger"></span>  
  21.             </div>  
  22.         </div>  
  23.         <div class="form-group">  
  24.             <label asp-for="LastName" class="col-md-2 control-label"></label>  
  25.             <div class="col-md-10">  
  26.                 <input asp-for="LastName" class="form-control" />  
  27.                 <span asp-validation-for="LastName" class="text-danger"></span>  
  28.             </div>  
  29.         </div>  
  30.         <div class="form-group">  
  31.             <label asp-for="Gender" class="col-md-2 control-label"></label>  
  32.             <div class="col-md-10">  
  33.                 <input asp-for="Gender" class="form-control" />  
  34.                 <span asp-validation-for="Gender" class="text-danger"></span>  
  35.             </div>  
  36.         </div>  
  37.         <div class="form-group">  
  38.             <label asp-for="DateOfBirth" class="col-md-2 control-label"></label>  
  39.             <div class="col-md-10">  
  40.                 <input asp-for="DateOfBirth" class="form-control" />  
  41.                 <span asp-validation-for="DateOfBirth" class="text-danger"></span>  
  42.             </div>  
  43.         </div>  
  44.         <div class="form-group">  
  45.             <label asp-for="DateOfRegistration" class="col-md-2 control-label"></label>  
  46.             <div class="col-md-10">  
  47.                 <input asp-for="DateOfRegistration" class="form-control" />  
  48.                 <span asp-validation-for="DateOfRegistration" class="text-danger"></span>  
  49.             </div>  
  50.         </div>  
  51.         <div class="form-group">  
  52.             <label asp-for="PhoneNumber" class="col-md-2 control-label"></label>  
  53.             <div class="col-md-10">  
  54.                 <input asp-for="PhoneNumber" class="form-control" />  
  55.                 <span asp-validation-for="PhoneNumber" class="text-danger"></span>  
  56.             </div>  
  57.         </div>  
  58.         <div class="form-group">  
  59.             <label asp-for="Email" class="col-md-2 control-label"></label>  
  60.             <div class="col-md-10">  
  61.                 <input asp-for="Email" class="form-control" />  
  62.                 <span asp-validation-for="Email" class="text-danger"></span>  
  63.             </div>  
  64.         </div>  
  65.         <div class="form-group">  
  66.             <label asp-for="Address1" class="col-md-2 control-label"></label>  
  67.             <div class="col-md-10">  
  68.                 <input asp-for="Address1" class="form-control" />  
  69.                 <span asp-validation-for="Address1" class="text-danger"></span>  
  70.             </div>  
  71.         </div>  
  72.         <div class="form-group">  
  73.             <label asp-for="Address2" class="col-md-2 control-label"></label>  
  74.             <div class="col-md-10">  
  75.                 <input asp-for="Address2" class="form-control" />  
  76.                 <span asp-validation-for="Address2" class="text-danger"></span>  
  77.             </div>  
  78.         </div>  
  79.         <div class="form-group">  
  80.             <label asp-for="City" class="col-md-2 control-label"></label>  
  81.             <div class="col-md-10">  
  82.                 <input asp-for="City" class="form-control" />  
  83.                 <span asp-validation-for="City" class="text-danger"></span>  
  84.             </div>  
  85.         </div>  
  86.         <div class="form-group">  
  87.             <label asp-for="State" class="col-md-2 control-label"></label>  
  88.             <div class="col-md-10">  
  89.                 <input asp-for="State" class="form-control" />  
  90.                 <span asp-validation-for="State" class="text-danger"></span>  
  91.             </div>  
  92.         </div>  
  93.         <div class="form-group">  
  94.             <label asp-for="Zip" class="col-md-2 control-label"></label>  
  95.             <div class="col-md-10">  
  96.                 <input asp-for="Zip" class="form-control" />  
  97.                 <span asp-validation-for="Zip" class="text-danger"></span>  
  98.             </div>  
  99.         </div>  
  100.         <div class="form-group">  
  101.             <div class="col-md-offset-2 col-md-10">  
  102.                 <input type="submit" value="Save" class="btn btn-default" />  
  103.             </div>  
  104.         </div>  
  105.     </div>  
  106. </form>  
  107.   
  108. <div>  
  109.     <a asp-action="Index">Back to List</a>  
  110. </div>  
  111.   
  112. @section Scripts {  
  113.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  114. }  

Delete

  1. @model StudentApplication.Web.Helper.StudentDTO  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Delete";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <strong>Delete</strong>  
  9.   
  10. <strong>Are you sure you want to delete this?</strong>  
  11. <div>  
  12.     <strong>Student</strong>  
  13.     <hr />  
  14.     <dl class="dl-horizontal">  
  15.         <input type="hidden" asp-for="StudentId" />  
  16.         <dt>  
  17.             @Html.DisplayNameFor(model => model.FirstName)  
  18.         </dt>  
  19.         <dd>  
  20.             @Html.DisplayFor(model => model.FirstName)  
  21.         </dd>  
  22.         <dt>  
  23.             @Html.DisplayNameFor(model => model.LastName)  
  24.         </dt>  
  25.         <dd>  
  26.             @Html.DisplayFor(model => model.LastName)  
  27.         </dd>  
  28.         <dt>  
  29.             @Html.DisplayNameFor(model => model.Gender)  
  30.         </dt>  
  31.         <dd>  
  32.             @Html.DisplayFor(model => model.Gender)  
  33.         </dd>  
  34.         <dt>  
  35.             @Html.DisplayNameFor(model => model.DateOfBirth)  
  36.         </dt>  
  37.         <dd>  
  38.             @Html.DisplayFor(model => model.DateOfBirth)  
  39.         </dd>  
  40.         <dt>  
  41.             @Html.DisplayNameFor(model => model.DateOfRegistration)  
  42.         </dt>  
  43.         <dd>  
  44.             @Html.DisplayFor(model => model.DateOfRegistration)  
  45.         </dd>  
  46.         <dt>  
  47.             @Html.DisplayNameFor(model => model.PhoneNumber)  
  48.         </dt>  
  49.         <dd>  
  50.             @Html.DisplayFor(model => model.PhoneNumber)  
  51.         </dd>  
  52.         <dt>  
  53.             @Html.DisplayNameFor(model => model.Email)  
  54.         </dt>  
  55.         <dd>  
  56.             @Html.DisplayFor(model => model.Email)  
  57.         </dd>  
  58.         <dt>  
  59.             @Html.DisplayNameFor(model => model.Address1)  
  60.         </dt>  
  61.         <dd>  
  62.             @Html.DisplayFor(model => model.Address1)  
  63.         </dd>  
  64.         <dt>  
  65.             @Html.DisplayNameFor(model => model.Address2)  
  66.         </dt>  
  67.         <dd>  
  68.             @Html.DisplayFor(model => model.Address2)  
  69.         </dd>  
  70.         <dt>  
  71.             @Html.DisplayNameFor(model => model.City)  
  72.         </dt>  
  73.         <dd>  
  74.             @Html.DisplayFor(model => model.City)  
  75.         </dd>  
  76.         <dt>  
  77.             @Html.DisplayNameFor(model => model.State)  
  78.         </dt>  
  79.         <dd>  
  80.             @Html.DisplayFor(model => model.State)  
  81.         </dd>  
  82.         <dt>  
  83.             @Html.DisplayNameFor(model => model.Zip)  
  84.         </dt>  
  85.         <dd>  
  86.             @Html.DisplayFor(model => model.Zip)  
  87.         </dd>  
  88.     </dl>  
  89.   
  90.     <form asp-action="Delete">  
  91.         <div class="form-actions no-color">  
  92.             <input type="submit" value="Delete" class="btn btn-default" /> |  
  93.             <a asp-action="Index">Back to List</a>  
  94.         </div>  
  95.     </form>  
  96. </div>  

All markup above is a strongly-typed View as all of them are referencing the same object Model which is StudentApplication.Web.Helper.StudentDTO. They also used tag-helpers to define the HTML and data binding.

Testing the Application

Since this demo is composed of two projects and our MVC application relies on our Web API application, we need  to make the Web API accessible when testing the page. Typically, we will host or deploy both projects in IIS web server to be able to connect between projects. Luckily, one of the cool features in Visual Studio 2017 is to enable multiple start-up projects. This means we could run both our Web API and MVC application within Visual Studio and be able to test them right away without having them to deploy in IIS. All you need to do is,

  1. Right click on the Solution
  2. Select Set Startup Projects
  3. Select Multiple Startup Projects radio button
  4. Select "Start" as the action for both Web API and MVC project
  5. Click Apply and then OK

Now, build and run the application using CTRL + 5. In the browser, navigate to /students/Create. It should bring up the following page.

ASP.NET Core
Figure 13: The Create View

Supply the fields and click the "Create" button and it should navigate you to the Index page with the newly student record added as shown inthe figure below,

ASP.NET Core
Figure 14: The Index View

Of course the Edit and Delete works too :) Feel free to download the source code and have fun!

Summary

In this series, we’ve learned building an ASP.NET Core MVC application using Entity Framework Core with new database. We also learned how to create a Web API Controller and have the Controller talked to an Interface. We also learned how to implement a simple Data Access using a repository pattern to handle CRUD operations. Finally we've learned how to create a basic ASP.NET Core MVC application that consumes a Web API endpoints to perform CRUD in the UI.

References
  • https://docs.microsoft.com/en-us/aspnet/core/
  • https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext
  • https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db
  • https://www.asp.net/web-api

Up Next
    Ebook Download
    View all
    Learn
    View all