Reader small image

You're reading from  Learning ASP.NET Core MVC Programming

Product typeBook
Published inNov 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781786463838
Edition1st Edition
Languages
Right arrow
Authors (2):
Mugilan T. S. Ragupathi
Mugilan T. S. Ragupathi
author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

Anuraj Parameswaran
Anuraj Parameswaran
author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran

View More author details
Right arrow

Chapter 5. Models

Data is the heart of every application. A user enters data into the application, edits the entered data, and searches the data. We can even say that an application that we build is just an interface for the operations that we perform on the application data. So, it is absolutely necessary for any framework to provide a mechanism to handle data operations easier and more manageable. Models in ASP.NET MVC are used to represent the business domain data.

In this chapter, you'll be learning about the following topics:

  • Models and their purpose

  • Creating a simple model and using it in the controller and views of the ASP.NET MVC application

  • Creating a model specific to a View model

  • Data flow in an ASP.NET MVC application in the context of models and ViewModels

  • Purpose of the Entity Framework along with its features and benefits

  • Adding, updating, and deleting data using the Entity Framework

  • Using the Entity Framework in ASP.NET MVC applications

Models


Models are simple POCO (Plain Old C# Objects) classes representing your business domain data. For an e-commerce business, model classes would be Product, Order, and Inventory. If you are building an application for a university, model classes would be Student, Teacher, and Subject. Models represent the business domain data in your application and they are not aware of the underlying database that is being used in your application. In fact, you don't even need a database to work with models.

They can represent the data stored in an XML file or CSV file or any other data in your application. Having said that, these models could be used to interact with your database (in most cases) but they don't have any dependency to the database.

The following steps describe how to create an ASP.NET Core application that uses Models:

  1. Make sure to create an ASP.NET 5 application with an empty template. Install the ASP.NET Core NuGet package and configure this, as discussed in an earlier chapter.

  2. Create...

Model binding


Model binding is the process of mapping the Model data coming from the View to the ViewModel parameter of the action method in the Controller.

Let us consider a simple form with a couple of form fields—Name and EmailID. On the submission of the form, these values would be mapped to the ViewModel object of the action method of the Controller. Model binding takes care of this mapping. The Model binder looks for a match in the form fields, query strings, and request parameters.

In the preceding example, any class with these properties would be picked up by ModelBinder without any issues.

As the following Person class contains the Name and EmailID properties, the model binder would not complain about using this model for mapping the entered values in the form:

public class Person { 
  public string Name { get; set; } 
  public string EmailID { get; set; } 
} 

The following code snippet shows how to use the Person class in the action method:

public ActionResult Add...

The Entity Framework


The Entity Framework is the Object Relational Mapping (ORM) framework that enables developers to work on domain-specific objects directly for data access instead of working on database queries. This reduces a lot of the code complexity in the data access layer in the application.

Before discussing the Entity Framework and its features, let us pause for a moment and think about the steps that we follow when we try to save some information to the database when using ADO.NET:

  1. Construct the business domain object.

  2. Create a connection to your database.

  3. Open the connection.

  4. Create a command object along with the command type.

  5. Add the properties of your business domain object to the parameters of the command object.

  6. Execute the command that saves the data into the database.

We have to follow the previously mentioned six steps for common operations such as saving a piece of data into the database.

If you are using an ORM framework such as the Entity Framework, you just need three steps...

Using the Entity Framework in ASP.NET MVC applications


There is not much difference between using the Entity Framework in a console application and ASP.NET MVC application. Now, we are going to build a simple application with a single screen as shown in the following image. In this screen, we will have a form where the user will enter the information about the employee; once the user submits the form, the information will be saved to the database and reflected in the following screenshots:

We can create a simple Model for the employee. We need to build a ViewModel for this View, as we need to get the employee information from the user and we need to show a list of employees as well on the same screen.

Let us create an ASP.NET Core application, adding the employee and showing the list of employees. The following is the step-by-step instructions to create the application for the previously mentioned objective:

  1. Create an ASP.NET Core project in Visual Studio by selecting an empty ASP.NET 5 application...

Database migration


We have created the business entity—the Employee class. Now, we can proceed with the migration. Migration is a two-step process: in the first step, we create the migration files. This can be done by executing the following command from the command prompt from the context of the project:

dnx ef migrations add InitialMigration

This command will create the migration files in your project, as shown in the following screenshot:

Then execute the following command to create the database:

This command will read the migration files created in the previous step and create the database along with the associated tables:

Run the application. You will get the following screen, where the user can enter the employee information in the form. As we are using the strongly typed model in our view, it takes the default values for all the properties. The Name and Designation are properties of type string and the default values are empty string for these fields, Salary is of type decimal...

Summary


In this chapter, we learned what a Model is and how it fits in the ASP.NET MVC application. Then, we created a simple Model, built model data in a Controller, passed the Model to the View, and shown the data using the View. We have learned about the Models specific to a View and have discussed the flow of the data with respect to Models. We learned about the Entity Framework, an ORM framework from Microsoft, and how it simplifies database access from your .NET application. We have created simple console application where we have inserted, updated, and deleted the records. Finally, we have built an ASP.NET Core application that uses Model, ViewModel, and Entity Framework.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning ASP.NET Core MVC Programming
Published in: Nov 2016Publisher: PacktISBN-13: 9781786463838
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (2)

author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran