Onion Architecture In ASP.NET Core MVC

Introduction

The Onion Architecture term was coined by Jeffrey Palermo in 2008. This architecture provides a better way to build applications for better testability, maintainability, and dependability on the infrastructures like databases and services. This architecture's main aim is to address the challenges faced with 3-tier architecture or n-tier architecture, and to provide a solution for common problems, like coupling and separation of concerns. There are two types of coupling - tight coupling and loose coupling.

Tight Coupling

When a class is dependent on a concrete dependency, it is said to be tightly coupled to that class. A tightly coupled object is dependent on another object; that means changing one object in a tightly coupled application, often requires changes to a number of other objects. It is not difficult when an application is small but in an enterprise level application, it is too difficult to make the changes.

Loose Coupling

It means two objects are independent and an object can use another object without being dependent on it. It is a design goal that seeks to reduce the inter-dependencies among components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.

Advantages of Onion Architecture

There are several advantages of the Onion Architecture, as listed below.

  1. It provides better maintainability as all the codes depend on layers or the center.
  2. It provides better testabilty as the unit test can be created for separate layers without an effect of other modules of the application.
  3. It develops a loosely coupled application as the outer layer of the application always communicates with inner layer via interfaces.
  4. Any concrete implantation would be provided to the application at run time
  5. Domain entities are core and center part. It can have access to both database and UI layers.
  6. The internal layers never depend on external layer. The code that may have changed should be part of an external layer.

Why Onion Architecture

There are several traditional architectures, like 3-tier architecture and n-tier architecture, all having their own pros and cons. All these traditional architectures have some fundamental issues, such as - tight coupling and separation of concerns. The Model-View-Controller is the most commonly used web application architecture, these days. It solves the problem of separation of concern as there is a separation between UI, business logic, and data access logic. The View is used to design the user interface. The Model is used to pass the data between View and Controller on which the business logic performs any operations. The Controller is used to handle the web request by action methods and returns View accordingly. Hence, it solves the problem of separation of concern while the Controller is still used to database access logic. In essence, MVC solves the separation of concern issue but the tight coupling issue still remains.

On the other hand, Onion Architecture addresses both the separation of concern and tight coupling issues. The overall philosophy of the Onion Architecture is to keep the business logic, data access logic, and model in the middle of the application and push the dependencies as far outward as possible means all coupling towards to center.

Onion Architecture Layers

This architecture relies heavily on the Dependency Inversion Principle. The UI communicates to business logic through interfaces. It has four layers, as shown in figure 1.
  1. Domain Entities Layer
  2. Repository Layer
  3. Service Layer
  4. UI (Web/Unit Test) Layer


Figure 1: Onion Architecture Layers

These layers are towards to center. The center part is the Domain entities which represent the business and behavior objects. These layers can vary but the domain entities layer is always part of the center. The other layer defines more behavior of an object. Let’s see each layer one by one.

  1. Domain Entities Layer
    It is the center part of the architecture. It holds all application domain objects. If an application is developed with ORM entity framework then this layer holds POCO classes (Code First) or Edmx (Database First) with entities. These domain entities don't have any dependencies.

  2. Repository Layer
    The layer is intended to create an Abstraction layer between the Domain entities layer and Business Logic layer of an application. It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which queries the data source for the data, maps the data from the data source to a business entity and persists changes in the business entity to the data source.

  3. Service Layer
    The layer holds interfaces which are used to communicate between the UI layer and repository layer. It holds business logic for an entity so it’s called business logic layer as well.

  4. UI Layer
    It’s the most external layer. It could be the web application, Web API or Unit Test project. This layer has an implementation of the Dependency Inversion Principle so that application builds a loosely coupled application. It communicates to internal layer via interfaces.

Onion Architecture Project Structure

To implement the Onion architecture, we develop an ASP.NET Core application. This application performs CRUD operations on entities. The application holds four projects as per figure 2. Each project represents a layer in onion architecture.


Figure 2: Application projects structure

There are four projects in which three are class library projects and one is web application project. Let’s see each project mapping with onion architecture layers.

  1. OA.Data
    It is a class library project. It holds POCO classes along with configuration classes. It represents the Domain Entities layer of the onion architecture. These classes are used to create database tables. It’s a core and central part of the application.

  2. OA.Repo
    It is a second class library project. It holds generic repository class with its interface implementation. It also holds DbContext class. The Entity Framework Code First data access approach needs to create a data access context class that inherits from the DbContext class. This project represents the Repository layer of the onion architecture.

  3. OA.Service
    It is a third class library project. It holds business logic and interfaces. These interfaces communicate between UI and data access logic. As it communicates via interfaces,  it builds applications that are  loosely coupled. This project represents the Service layer of the onion architecture.

  4. OA.Web
    It is an ASP.NET Core Web application in this sample but it could be Unit Test or Web API project. It is the most external part of an application by which the end user can interact with the application. It builds loosely coupled applications with in-built dependency injection in ASP.NET Core. It represents the UI layer of the onion architecture.

Implement Onion Architecture

To implement the Onion Architecture in the ASP.NET Core application, create four projects as described in the above section. These four projects represent four layers of the onion architecture. Let’s see each one by one.

Domain Entities Layer

The Entities Domain layer is a core and central part of the architecture. So first, we create "OA.Data" project to implement this layer. This project holds POCO class and fluent API configuration for this POCO classes.

There is an unsupported issue of EF Core 1.0.0-preview2-final with "NETStandard.Library": "1.6.0". Thus, we have changed the target framework to netstandard1.6 > netcoreapp1.0. We modify the project.json file of OA.Data project to implement the Entity Framework Core in this class library project. Thus, the code snippet, mentioned below, is used for the project.json file after modification.

  1. {  
  2.   "dependencies": {  
  3.     "Microsoft.EntityFrameworkCore.SqlServer""1.0.0",  
  4.     "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  
  5.   },  
  6.   "frameworks": {  
  7.     "netcoreapp1.0": {  
  8.       "imports": [ "dotnet5.6""portable-net45+win8" ]  
  9.     }  
  10.   },  
  11.   "tools": {  
  12.     "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  
  13.   },  
  14.   "version""1.0.0-*"  
  15. }  
This Application uses the Entity Framework Code First approach, so the project OA.Data contains entities that are required in the application's database. The OA.Data project holds three entities, one is the BaseEntity class that has common properties that will be inherited by each entity. The code snippet, mentioned below is the BaseEntity class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace OA.Data  
  7. {  
  8.     public class BaseEntity  
  9.     {  
  10.         public Int64 Id { get; set; }  
  11.         public DateTime AddedDate { get; set; }  
  12.         public DateTime ModifiedDate { get; set; }  
  13.         public string IPAddress { get; set; }  
  14.     }  
  15. }  
There are two more entities, one is User and the another one is UserProfile. Both entities have a one to one relationship, as shown below.


Figure 3: One to One User-UserProfile relationship

Now, we create an User entity, which is inherited from BaseEntity class. The code snippet, mentioned below is for the User entity.
  1. namespace OA.Data  
  2. {  
  3.     public class User:BaseEntity  
  4.     {  
  5.         public string UserName { get; set; }  
  6.         public string Email { get; set; }  
  7.         public string Password { get; set; }  
  8.         public virtual UserProfile UserProfile { get; set; }  
  9.     }  
  10. }  
Now, we define the configuration for the User entity that will be used when the database table will be created by the entity. The following is a code snippet for the User mapping entity (UserMap.cs).
  1. using Microsoft.EntityFrameworkCore.Metadata.Builders;  
  2.   
  3. namespace OA.Data  
  4. {  
  5.     public class UserMap  
  6.     {  
  7.         public UserMap(EntityTypeBuilder<User> entityBuilder)  
  8.         {  
  9.             entityBuilder.HasKey(t => t.Id);  
  10.             entityBuilder.Property(t => t.Email).IsRequired();  
  11.             entityBuilder.Property(t => t.Password).IsRequired();  
  12.             entityBuilder.Property(t => t.Email).IsRequired();  
  13.             entityBuilder.HasOne(t => t.UserProfile).WithOne(u => u.User).HasForeignKey<UserProfile>(x => x.Id);  
  14.         }  
  15.     }  
  16. }  
Now, we create a UserProfile entity, which inherits from the BaseEntity class. The code snippet, mentioned below is for the UserProfile entity.
  1. namespace OA.Data  
  2. {  
  3.     public class UserProfile:BaseEntity  
  4.     {  
  5.         public string FirstName { get; set; }  
  6.         public string LastName { get; set; }  
  7.         public string Address { get; set; }  
  8.         public virtual User User { get; set; }  
  9.     }  
  10. }  
Now, we define the configuration for the UserProfile entity that will be used when the database table will be created by the entity. The code snippet is mentioned below for the UserProfile mapping entity (UserProfileMap.cs).
  1. using Microsoft.EntityFrameworkCore.Metadata.Builders;  
  2.   
  3. namespace OA.Data  
  4. {  
  5.     public class UserProfileMap  
  6.     {  
  7.         public UserProfileMap(EntityTypeBuilder<UserProfile> entityBuilder)  
  8.         {  
  9.             entityBuilder.HasKey(t => t.Id);  
  10.             entityBuilder.Property(t => t.FirstName).IsRequired();  
  11.             entityBuilder.Property(t => t.LastName).IsRequired();  
  12.             entityBuilder.Property(t => t.Address);    
  13.         }  
  14.     }  
  15. }  
Repository Layer

Now we create a second layer of the onion architecture which is repository layer. To build this layer, we create one more class library project named OA.Repo. This project holds both repository and data context classes.

The OA.Repo project contains DataContext. The ADO.NET Entity Framework Code First data access approach needs to create a data access context class that inherits from the DbContext class, so we create a context class ApplicationContext (ApplicationContext.cs) class.

In this class, we override the OnModelCreating() method. This method is called when the model for a context class (ApplicationContext) has been initialized, but before the model has been locked down and used to initialize the context such that the model can be further configured before it is locked down. The following is the code snippet for the context class.
  1. using Microsoft.EntityFrameworkCore;  
  2. using OA.Data;  
  3.   
  4. namespace OA.Repo  
  5. {  
  6.     public class ApplicationContext : DbContext  
  7.     {  
  8.         public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)  
  9.         {  
  10.         }  
  11.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  12.         {  
  13.             base.OnModelCreating(modelBuilder);  
  14.             new UserMap(modelBuilder.Entity<User>());  
  15.             new UserProfileMap(modelBuilder.Entity<UserProfile>());  
  16.         }  
  17.     }  
  18. }  
The DbContext must have an instance of DbContextOptions in order to execute. We will use dependency injection, so we pass options via constructor dependency injection. ASP.NET Core is designed from the ground to support and leverage dependency injection. Thus, we create generic repository interface for the entity operations, so that we can develop loosely coupled application. The code snippet, mentioned below is for the IRepository interface.
  1. using OA.Data;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace OA.Repo  
  5. {  
  6.     public interface IRepository<T> where T : BaseEntity  
  7.     {  
  8.         IEnumerable<T> GetAll();  
  9.         T Get(long id);  
  10.         void Insert(T entity);  
  11.         void Update(T entity);  
  12.         void Delete(T entity);  
  13.         void Remove(T entity);  
  14.         void SaveChanges();  
  15.     }  
  16. }  
Now, let's create a repository class to perform database operations on the entity, which implements IRepository. This repository contains a parameterized constructor with a parameter as Context, so when we create an instance of the repository, we pass a context so that the entity has the same context. The code snippet is mentioned below for the Repository class under OA.Repo project.
  1. using Microsoft.EntityFrameworkCore;  
  2. using OA.Data;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6.   
  7. namespace OA.Repo  
  8. {  
  9.     public class Repository<T> : IRepository<T> where T : BaseEntity  
  10.     {  
  11.         private readonly ApplicationContext context;  
  12.         private DbSet<T> entities;  
  13.         string errorMessage = string.Empty;  
  14.   
  15.         public Repository(ApplicationContext context)  
  16.         {  
  17.             this.context = context;  
  18.             entities = context.Set<T>();  
  19.         }  
  20.         public IEnumerable<T> GetAll()  
  21.         {  
  22.             return entities.AsEnumerable();  
  23.         }  
  24.   
  25.         public T Get(long id)  
  26.         {  
  27.             return entities.SingleOrDefault(s => s.Id == id);  
  28.         }  
  29.         public void Insert(T entity)  
  30.         {  
  31.             if (entity == null)  
  32.             {  
  33.                 throw new ArgumentNullException("entity");  
  34.             }  
  35.             entities.Add(entity);  
  36.             context.SaveChanges();  
  37.         }  
  38.   
  39.         public void Update(T entity)  
  40.         {  
  41.             if (entity == null)  
  42.             {  
  43.                 throw new ArgumentNullException("entity");  
  44.             }  
  45.             context.SaveChanges();  
  46.         }  
  47.   
  48.         public void Delete(T entity)  
  49.         {  
  50.             if (entity == null)  
  51.             {  
  52.                 throw new ArgumentNullException("entity");  
  53.             }  
  54.             entities.Remove(entity);  
  55.             context.SaveChanges();  
  56.         }  
  57.         public void Remove(T entity)  
  58.         {  
  59.             if (entity == null)  
  60.             {  
  61.                 throw new ArgumentNullException("entity");  
  62.             }  
  63.             entities.Remove(entity);              
  64.         }  
  65.   
  66.         public void SaveChanges()  
  67.         {  
  68.             context.SaveChanges();  
  69.         }  
  70.     }  
  71. }  
We developed entity and context which are required to create a database but we will come back to this after creating the two more projects.

Service Layer

Now we create the third layer of the onion architecture which is service layer. To build this layer, we create one more class library project named OA.Service. This project holds interfaces and classes which have implementation of interfaces. This layer  is intended to build loosely coupled applications. This layer communicates to both Web applications and repository projects.

We create an interface named IUserService. This interface holds all methods signature which access by external layer for the User entity. The following code snippet is for the same (IUserService.cs).
  1. using OA.Data;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace OA.Service  
  5. {  
  6.     public  interface IUserService  
  7.     {  
  8.         IEnumerable<User> GetUsers();  
  9.         User GetUser(long id);  
  10.         void InsertUser(User user);  
  11.         void UpdateUser(User user);  
  12.         void DeleteUser(long id);  
  13.     }  
  14. }  
Now, this IUserService interface implements on a class named UserService. This UserService class holds all the operations for User entity. The following code snippet is for the same(UserService.cs).
  1. using OA.Data;  
  2. using OA.Repo;  
  3. using System.Collections.Generic;  
  4.   
  5. namespace OA.Service  
  6. {  
  7.     public class UserService:IUserService  
  8.     {  
  9.         private IRepository<User> userRepository;  
  10.         private IRepository<UserProfile> userProfileRepository;  
  11.   
  12.         public UserService(IRepository<User> userRepository, IRepository<UserProfile> userProfileRepository)  
  13.         {  
  14.             this.userRepository = userRepository;  
  15.             this.userProfileRepository = userProfileRepository;  
  16.         }  
  17.   
  18.         public IEnumerable<User> GetUsers()  
  19.         {  
  20.             return userRepository.GetAll();  
  21.         }  
  22.   
  23.         public User GetUser(long id)  
  24.         {  
  25.             return userRepository.Get(id);  
  26.         }  
  27.   
  28.         public void InsertUser(User user)  
  29.         {  
  30.             userRepository.Insert(user);  
  31.         }  
  32.         public void UpdateUser(User user)  
  33.         {  
  34.             userRepository.Update(user);  
  35.         }  
  36.   
  37.         public void DeleteUser(long id)  
  38.         {              
  39.             UserProfile userProfile = userProfileRepository.Get(id);  
  40.             userProfileRepository.Remove(userProfile);  
  41.             User user = GetUser(id);  
  42.             userRepository.Remove(user);  
  43.             userRepository.SaveChanges();  
  44.         }  
  45.     }  
  46. }  
We create one more interface named IUserProfileService. This interface holds method signature which is accessed by the external layer for the UserProfile entity. The following code snippet is for the same (IUserProfileService.cs).
  1. using OA.Data;  
  2.   
  3. namespace OA.Service  
  4. {  
  5.     public interface IUserProfileService  
  6.     {  
  7.         UserProfile GetUserProfile(long id);  
  8.     }  
  9. }  
Now, this IUserProfileService interface implements on a class named UserProfileService. This UserProfileService class holds the operation for UserProfile entity. The following code snippet is for the same(UserProfileService.cs).
  1. using OA.Data;  
  2. using OA.Repo;  
  3.   
  4. namespace OA.Service  
  5. {  
  6.     public class UserProfileService: IUserProfileService  
  7.     {  
  8.         private IRepository<UserProfile> userProfileRepository;  
  9.   
  10.         public UserProfileService(IRepository<UserProfile> userProfileRepository)  
  11.         {             
  12.             this.userProfileRepository = userProfileRepository;  
  13.         }  
  14.   
  15.         public UserProfile GetUserProfile(long id)  
  16.         {  
  17.             return userProfileRepository.Get(id);  
  18.         }  
  19.     }  
  20. }  
UI Layer

Now, we create the external layer of the onion architecture which is UI layer. The end user interacts with the application by this layer. To build this layer, we create an ASP.NET Core MVC web application named OA.Web. This layer communicates to service layer projects. This project contains the user interface for both user and user profile entities database operations and the controller to do these operations.

As the concept of dependency injection is central to the ASP.NET Core application, we register context, repository, and service to the dependency injection during the application start up. Thus, we register these as a Service in the ConfigureServices method in the StartUp class as per following code snippet.
  1. public void ConfigureServices(IServiceCollection services)  
  2.       {             
  3.           services.AddMvc();  
  4.           services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  5.           services.AddScoped(typeof(IRepository<>), typeof(Repository<>));  
  6.           services.AddTransient<IUserService, UserService>();  
  7.           services.AddTransient<IUserProfileService, UserProfileService>();  
  8.       }  
Here, the DefaultConnection is connection string which defined in appsettings.json file as per following code snippet.
  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""Data Source=DESKTOP-RG33QHE;Initial Catalog=OADb;User ID=sa; Password=***"  
  4.   },  
  5.   "Logging": {  
  6.     "IncludeScopes"false,  
  7.     "LogLevel": {  
  8.       "Default""Debug",  
  9.       "System""Information",  
  10.       "Microsoft""Information"  
  11.     }  
  12.   }  
  13. }  
Now, we have configured settings to create database, so we have time to create a database, using migration. We must choose the OA.Repo project in the Package Manager console during the performance of the steps, mentioned below.

 

  1. Tools -> NuGet Package Manager -> Package Manager Console
  2. Run PM> Add-Migration MyFirstMigration to scaffold a migration to create the initial set of tables for our model. If we receive an error stating the term `add-migration' is not recognized as the name of a cmdlet, then close and reopen Visual Studio.
  3. Run PM> Update-Database to apply the new migration to the database. Because our database doesn't exist yet, it will be created for us before the migration is applied.

Create Application User Interface

Now, we proceed to the controller. We create controller named UserController under the Controllers folder of the application. It has all ActionResult methods for end user interface of operations. We create both IUserService and IUserProfile interface instances; then we inject these in the controller's constructor to get its object. The following is a partial code snippet for the UserController in which service interfaces are injected, using constructor dependency injection.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using OA.Service;  
  6. using OA.Web.Models;  
  7. using OA.Data;  
  8. using Microsoft.AspNetCore.Http;  
  9.   
  10. namespace OA.Web.Controllers  
  11. {  
  12.     public class UserController : Controller  
  13.     {  
  14.         private readonly IUserService userService;  
  15.         private readonly IUserProfileService userProfileService;  
  16.   
  17.         public UserController(IUserService userService, IUserProfileService userProfileService)  
  18.         {  
  19.             this.userService = userService;  
  20.             this.userProfileService = userProfileService;  
  21.         }  
  22.     }  
  23. }  
We can notice that Controller takes both IUserService and IUserProfileService as a constructor parameters. The ASP.NET Core dependency injection will take care of passing an instance of these services into UserController. The controller is developed to handle operations requests for both User and UserProfile entities. Now, let's develop the user interface for the User Listing, Add User, Edit User and Delete User. Let's see each one by one.

User List View

This is the first view when the application is accessed or the entry point of the application is executed. It shows the author listing as in Figure 4. The user data is displayed in a tabular format and on this view, it has linked to add a new user, edit a user and delete a user.

To pass data from controller to view, create named UserViewModel view model, as per the code snippet, mentioned below. This view model is also used for adding or editing a user.
  1. using Microsoft.AspNetCore.Mvc;  
  2. using System;  
  3. using System.ComponentModel.DataAnnotations;  
  4.   
  5. namespace OA.Web.Models  
  6. {  
  7.     public class UserViewModel  
  8.     {  
  9.         [HiddenInput]  
  10.         public Int64 Id { get; set; }  
  11.         [Display(Name = "First Name")]  
  12.         public string FirstName { get; set; }  
  13.         [Display(Name = "Last Name")]  
  14.         public string LastName { get; set; }  
  15.         public string Name { get; set; }  
  16.         public string Address { get; set; }  
  17.         [Display(Name = "User Name")]  
  18.         public string UserName { get; set; }  
  19.         public string Email { get; set; }  
  20.         public string Password { get; set; }  
  21.         [Display(Name = "Added Date")]  
  22.         public DateTime AddedDate { get; set; }  
  23.     }  
  24. }  
Now, we create action method, which returns an index view with the data. The code snippet of Index action method in UserController is mentioned below.
  1. [HttpGet]  
  2.         public IActionResult Index()  
  3.         {  
  4.             List<UserViewModel> model = new List<UserViewModel>();  
  5.             userService.GetUsers().ToList().ForEach(u =>  
  6.             {  
  7.                 UserProfile userProfile = userProfileService.GetUserProfile(u.Id);  
  8.                 UserViewModel user = new UserViewModel  
  9.                 {  
  10.                     Id = u.Id,  
  11.                     Name = $"{userProfile.FirstName} {userProfile.LastName}",  
  12.                     Email = u.Email,  
  13.                     Address = userProfile.Address  
  14.                 };  
  15.                 model.Add(user);  
  16.             });  
  17.   
  18.             return View(model);  
  19.         }  
Now, we create an index view, as per the code snippet, mentioned below under the User folder of views.
  1. @model IEnumerable<UserViewModel>  
  2. @using OA.Web.Models  
  3. @using OA.Web.Code  
  4.   
  5. <div class="top-buffer"></div>  
  6. <div class="panel panel-primary">  
  7.     <div class="panel-heading panel-head">Users</div>  
  8.     <div class="panel-body">  
  9.         <div class="btn-group">  
  10.             <a id="createEditUserModal" data-toggle="modal" asp-action="AddUser" data-target="#modal-action-user" class="btn btn-primary">  
  11.                 <i class="glyphicon glyphicon-plus"></i>  Add User  
  12.             </a>  
  13.         </div>  
  14.         <div class="top-buffer"></div>  
  15.         <table class="table table-bordered table-striped table-condensed">  
  16.             <thead>  
  17.                 <tr>  
  18.                     <th>Name</th>  
  19.                     <th>Email</th>  
  20.                     <th>Address</th>  
  21.                     <th>Action</th>  
  22.                 </tr>  
  23.             </thead>  
  24.             <tbody>  
  25.                 @foreach (var item in Model)  
  26.                 {  
  27.                     <tr>  
  28.                         <td>@Html.DisplayFor(modelItem => item.Name)</td>  
  29.                         <td>@Html.DisplayFor(modelItem => item.Email)</td>  
  30.                         <td>@Html.DisplayFor(modelItem => item.Address)</td>  
  31.                         <td>  
  32.                             <a id="editUserModal" data-toggle="modal" asp-action="EditUser" asp-route-id="@item.Id" data-target="#modal-action-user"  
  33.                                class="btn btn-info">  
  34.                                 <i class="glyphicon glyphicon-pencil"></i>  Edit  
  35.                             </a>                           
  36.                             <a id="deleteUserModal" data-toggle="modal" asp-action="DeleteUser" asp-route-id="@item.Id" data-target="#modal-action-user" class="btn btn-danger">  
  37.                                 <i class="glyphicon glyphicon-trash"></i>  Delete  
  38.                             </a>  
  39.                         </td>  
  40.                     </tr>  
  41.                 }  
  42.             </tbody>  
  43.         </table>  
  44.     </div>  
  45. </div>  
  46.   
  47. @Html.Partial("_Modal"new BootstrapModel { ID = "modal-action-user", AreaLabeledId = "modal-action-user-label", Size = ModalSize.Large })  
  48.   
  49. @section scripts  
  50. {  
  51.     <script src="~/js/user-index.js" asp-append-version="true"></script>  
  52. }  
It shows all forms in the Bootstrap model popup so create the user - index.js file as per the following code snippet.
  1. (function ($) {  
  2. function User() {  
  3. var $this = this;  
  4.   
  5. function initilizeModel() {  
  6. $("#modal-action-user").on('loaded.bs.modal'function (e) {  
  7.   
  8. }).on('hidden.bs.modal'function (e) {  
  9. $(this).removeData('bs.modal');  
  10. });  
  11. }  
  12. $this.init = function () {  
  13. initilizeModel();  
  14. }  
  15. }  
  16. $(function () {  
  17. var self = new User();  
  18. self.init();  
  19. })  
  20. }(jQuery))  
When the application runs and calls the index() action method from UserController with a HttpGet request, it gets all the users listed in the UI, as shown in Figure 4.


Figure 4: User listing

Add User

To pass the data from UI to controller to add a user, use same view model named UserViewModel. The AuthorController has an action method named AddUser which returns view to add a user. The code snippet mentioned below is for same action method for both GET and Post requests.
  1. [HttpGet]  
  2.         public ActionResult AddUser()  
  3.         {  
  4.             UserViewModel model = new UserViewModel();  
  5.   
  6.             return PartialView("_AddUser", model);  
  7.         }  
  8.   
  9.         [HttpPost]  
  10.         public ActionResult AddUser(UserViewModel model)  
  11.         {  
  12.             User userEntity = new User  
  13.             {  
  14.                 UserName = model.UserName,  
  15.                 Email = model.Email,  
  16.                 Password = model.Password,  
  17.                 AddedDate = DateTime.UtcNow,  
  18.                 ModifiedDate = DateTime.UtcNow,  
  19.                 IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(),  
  20.                 UserProfile = new UserProfile  
  21.                 {  
  22.                     FirstName = model.FirstName,  
  23.                     LastName = model.LastName,  
  24.                     Address = model.Address,  
  25.                     AddedDate = DateTime.UtcNow,  
  26.                     ModifiedDate = DateTime.UtcNow,  
  27.                     IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString()  
  28.                 }  
  29.             };  
  30.             userService.InsertUser(userEntity);  
  31.             if (userEntity.Id > 0)  
  32.             {  
  33.                 return RedirectToAction("index");  
  34.             }  
  35.             return View(model);  
  36.         }  
The GET request for the AddUser action method returns _AddUser partial view; the code snippet follows under the User folder of views.
  1. @model UserViewModel  
  2. @using OA.Web.Models  
  3.   
  4. <form asp-action="AddUser" role="form">  
  5.     @await Html.PartialAsync("_ModalHeader"new ModalHeader { Heading = "Add User" })  
  6.     <div class="modal-body form-horizontal">  
  7.         <div class="row">  
  8.             <div class="col-lg-6">  
  9.                 <div class="form-group">  
  10.                     <label asp-for="FirstName" class="col-lg-3 col-sm-3 control-label"></label>  
  11.                     <div class="col-lg-6">  
  12.                         <input asp-for="FirstName" class="form-control" />  
  13.                     </div>  
  14.                 </div>  
  15.                 <div class="form-group">  
  16.                     <label asp-for="LastName" class="col-lg-3 col-sm-3 control-label"></label>  
  17.                     <div class="col-lg-6">  
  18.                         <input asp-for="LastName" class="form-control" />  
  19.                     </div>  
  20.                 </div>  
  21.                 <div class="form-group">  
  22.                     <label asp-for="Email" class="col-lg-3 col-sm-3 control-label"></label>  
  23.                     <div class="col-lg-6">  
  24.                         <input asp-for="Email" class="form-control" />  
  25.                     </div>  
  26.                 </div>  
  27.             </div>  
  28.             <div class="col-lg-6">  
  29.                 <div class="form-group">  
  30.                     <label asp-for="UserName" class="col-lg-3 col-sm-3 control-label"></label>  
  31.                     <div class="col-lg-6">  
  32.                         <input asp-for="UserName" class="form-control" />  
  33.                     </div>  
  34.                 </div>  
  35.                 <div class="form-group">  
  36.                     <label asp-for="Password" class="col-lg-3 col-sm-3 control-label"></label>  
  37.                     <div class="col-lg-6">  
  38.                         <input type="password" asp-for="Password" class="form-control" />  
  39.                     </div>  
  40.                 </div>  
  41.                 <div class="form-group">  
  42.                     <label asp-for="Address" class="col-lg-3 col-sm-3 control-label"></label>  
  43.                     <div class="col-lg-6">  
  44.                         <input asp-for="Address" class="form-control" />  
  45.                     </div>  
  46.                 </div>  
  47.             </div>  
  48.         </div>  
  49.     </div>  
  50.     @await Html.PartialAsync("_ModalFooter"new ModalFooter { })  
  51. </form>  
When the application runs and you click on the Add User button, it makes a GET request for the AddUser() action; add a user screen, as shown in Figure 5.


Figure 5: Add User screen

Edit User

To pass the data from UI to controller to edit a user, use same view model named UserViewModel. The UserController has an action method named EditUser, which returns view to edit a user. The code snippet mentioned below is  for the same action method for both GET and Post requests.
  1. public ActionResult EditUser(int? id)  
  2.       {  
  3.           UserViewModel model = new UserViewModel();  
  4.           if (id.HasValue && id != 0)  
  5.           {  
  6.               User userEntity = userService.GetUser(id.Value);  
  7.               UserProfile userProfileEntity = userProfileService.GetUserProfile(id.Value);  
  8.               model.FirstName = userProfileEntity.FirstName;  
  9.               model.LastName = userProfileEntity.LastName;  
  10.               model.Address = userProfileEntity.Address;  
  11.               model.Email = userEntity.Email;  
  12.           }  
  13.           return PartialView("_EditUser", model);  
  14.       }  
  15.   
  16.       [HttpPost]  
  17.       public ActionResult EditUser(UserViewModel model)  
  18.       {  
  19.           User userEntity = userService.GetUser(model.Id);  
  20.           userEntity.Email = model.Email;  
  21.           userEntity.ModifiedDate = DateTime.UtcNow;  
  22.           userEntity.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();  
  23.           UserProfile userProfileEntity = userProfileService.GetUserProfile(model.Id);  
  24.           userProfileEntity.FirstName = model.FirstName;  
  25.           userProfileEntity.LastName = model.LastName;  
  26.           userProfileEntity.Address = model.Address;  
  27.           userProfileEntity.ModifiedDate = DateTime.UtcNow;  
  28.           userProfileEntity.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();  
  29.           userEntity.UserProfile = userProfileEntity;  
  30.           userService.UpdateUser(userEntity);  
  31.           if (userEntity.Id > 0)  
  32.           {  
  33.               return RedirectToAction("index");  
  34.           }  
  35.           return View(model);  
  36.       }  
The GET request for the EditUser action method returns _EditUser partial view, where code snippet follows under the User folder of views.
  1. @model UserViewModel  
  2. @using OA.Web.Models  
  3.   
  4. <form asp-action="EditUser" role="form">  
  5.     @await Html.PartialAsync("_ModalHeader"new ModalHeader { Heading = "Edit User" })  
  6.     <div class="modal-body form-horizontal">  
  7.         <div class="row">              
  8.             <input asp-for="Id" />  
  9.                 <div class="form-group">  
  10.                     <label asp-for="FirstName" class="col-lg-3 col-sm-3 control-label"></label>  
  11.                     <div class="col-lg-6">  
  12.                         <input asp-for="FirstName" class="form-control" />  
  13.                     </div>  
  14.                 </div>  
  15.                 <div class="form-group">  
  16.                     <label asp-for="LastName" class="col-lg-3 col-sm-3 control-label"></label>  
  17.                     <div class="col-lg-6">  
  18.                         <input asp-for="LastName" class="form-control" />  
  19.                     </div>  
  20.                 </div>  
  21.                 <div class="form-group">  
  22.                     <label asp-for="Email" class="col-lg-3 col-sm-3 control-label"></label>  
  23.                     <div class="col-lg-6">  
  24.                         <input asp-for="Email" class="form-control" />  
  25.                     </div>  
  26.                 </div>           
  27.             
  28.                 <div class="form-group">  
  29.                     <label asp-for="Address" class="col-lg-3 col-sm-3 control-label"></label>  
  30.                     <div class="col-lg-6">  
  31.                         <input asp-for="Address" class="form-control" />  
  32.                     </div>  
  33.                 </div>  
  34.               
  35.         </div>  
  36.     </div>  
  37.     @await Html.PartialAsync("_ModalFooter"new ModalFooter { })  
  38. </form>  
When the application runs and you click on the Edit button in the User listing, it makes a GET request for the EditUser() action, then the edit user screen is shown in Figure 6.


Figure 6: Edit User

Delete User

The UserController has an action method named DeleteUser, which returns view to delete a user. The code snippet mentioned below is for the same action method for both GET and Post requests.
  1. [HttpGet]  
  2.         public PartialViewResult DeleteUser(int id)  
  3.         {  
  4.             UserProfile userProfile = userProfileService.GetUserProfile(id);  
  5.             string name = $"{userProfile.FirstName} {userProfile.LastName}";  
  6.             return PartialView("_DeleteUser", name);  
  7.         }  
  8.   
  9.         [HttpPost]  
  10.         public ActionResult DeleteUser(long id, FormCollection form)  
  11.         {  
  12.             userService.DeleteUser(id);            
  13.             return RedirectToAction("Index");  
  14.         }  
The GET request for the DeleteUser action method returns _DeleteUser partial View. The code snippet mentioned below is under the User folder of Views.
  1. @using OA.Web.Models  
  2.   
  3. <form asp-action="DeleteUser" role="form">  
  4.     @Html.Partial("_ModalHeader"new ModalHeader { Heading = "Delete User" })  
  5.   
  6.     <div class="modal-body form-horizontal">  
  7.         Are you want to delete @Model?  
  8.     </div>  
  9.     @Html.Partial("_ModalFooter"new ModalFooter { SubmitButtonText = "Delete" })  
  10. </form>  
When the application runs and user clicks on the "Delete" button in the user listing, it makes a GET request for the
DeleteUser() action, then the delete user screen is shown, as below.


Figure 7: Delete User

Download

You can download the complete source code from the MSDN Sample, using the links, mentioned below.

 

  1. Rating Star Application ASP.NET Core
  2. CRUD Operations in ASP.NET Core and Entity Framework Core
  3. Repository Pattern in ASP.NET Core
  4. Generic Repository Pattern in ASP.NET Core
  5. Onion Architecture In ASP.NET Core MVC

See Also

It's recommended to read more articles related to ASP.NET Core.

  1. Overview of ASP.NET Core
  2. ASP.NET Core With Visual Studio 2017 RC
  3. CRUD operations In ASP.NET Core Using Entity Framework Core Code First
  4. Repository Pattern In ASP.NET Core
  5. Generic Repository Pattern In ASP.NET Core
  6. Onion Architecture In ASP.NET Core MVC

Conclusion

This article introduced Onion Architecture in ASP.NET Core, using Entity Framework Core with the "code first" development approach. It’s widely accepted architecture these days. We used Bootstrap, CSS, and JavaScript for the user interface design in this application.

Up Next
    Ebook Download
    View all
    Learn
    View all