L2 ASP - NET MVC Code First Approach - 075015
L2 ASP - NET MVC Code First Approach - 075015
In this lecture we will learn how to achieve the code first approach by using Entity
Framework Core migration. Migration always helps us to create, update and sync the database
with the model classes.
A mechanism that maps objects (whose classes are called entities) to tables. This allows
you to work with data from databases using an object-oriented approach. Some examples of
object relational mappers: Entity Framework Core, Django, and Hibernate.
Entity Framework
It’s an object-relational mapping (ORM) framework and understands how to store .NET
objects in a relational database and retrieve those same objects given a LINQ query.
Entity Framework, follows a number of conventions to make your life easier. For
example, if you want to store an object of type Customer in the database, Entity Framework
assumes you want to store the data in a table named Customer. If you have a property on the
object named ID, Entity Framework assumes the property holds the primary key value and sets
up an auto-incrementing (identity) key column in SQL Server to hold the property value
In general, we need to perform the following steps
Step1: Create a new ASP.NET MVC project and install the required NuGet packages.
Step2: Create the model class and add the required data annotations.
Model in MVC
Before creating the applications, let’s remember the concept of model in MVC.
Model in MVC is a normal C# class that represent a data object. For example if our application is
about e-commerce web application, then we could have different model objects such as Users,
Categories, Products, Orders, etc. In other words models are the objects you want to display,
save, create, update, and delete.
Step1: Create a new ASP.NET MVC project and install the required NuGet packages.
Open visual studio and create a new project of type (ASP.NET Core Web App (Model- View-
Controller)).
Step2: Create the model class and add the required data annotations
Such a property will be mapped as the primary key of the corresponding table, to uniquely
identify each row in the table.
Data Annotations
Data annotations will be used for the model validation process which is enforcing the
requirements that an application has for the data it receives from clients. Without validation, an
application will try to operate on any data it receives, which can lead to exceptions and
unexpected behaviors that appear immediately or long-term problems that appear gradually as
the database is populated with bad, incomplete, or malicious data.
Model validation can be done using Validation Attributes. Some of the Built-in
Validation Attributes are listed in the table below.
Note2: if the properties using EmailAddress, Phone, Url are not [Required], then empty values
will pass the validation check.
Step3: Add the connection string to appsettings.json file.
"ConnectionStrings":{
DbContext class
– Data operations (adding data, modifying data, deleting data, and data querying);
– Change tracking (it keeps track of changes in your application—so you can save them
to the database);
– DbSet<TEntity> classes are added as properties to our class derived from DbContext;
– Each DbSet property represents the data (as a collection) from one table in the
database;
– We’ll use this to perform database operations for one table; – by default, entity/model
properties are mapped to database columns with the same name.
In this step, we’ll create a class derived from the class DbContext. As mentioned above, this
class will be responsible for connecting to the database and performing various operations,
among other things.
First, let’s create a new folder in our project and give it a name. We chose Data, but feel free to
give it a better name if you prefer. In this newly added folder, Data, create a new class (we called
it OurDbContext) derived from DbContext. In it, make sure to add the using directive:
using Microsoft.EntityFrameworkCore.Tools;
We need to define a non-default constructor in this class. The parameters we’ll pass to this
constructor will actually need to be passed along to the constructor of the base class
(DbContext); hence, we need to make sure that the non-default constructor of OurDbContext
calls the non-default constructor of DbContext and passes these parameters along. Here is how
we accomplish this. Add the following constructor to the OurDbContext class.
public OurDbContext(DbContextOptions<OurDbContext>options):base(options)
{
}
using ASPNETCodeFirst.Models;
using Microsoft.EntityFrameworkCore;
namespace ASPNETCodeFirst.Data
{
public class OurDbContext : DbContext
{
public OurDbContext(DbContextOptions<OurDbContext>options):base(options)
{
}
}
}
In this class, we will need to create a DbSet property for each table in the database. The name
that we choose for each DbSet property will be used when creating/using the table in the
database (of course we can use attributes to override this if needed). The DbSet is a generic class,
and it needs to know what entity class to work with—essentially each row in the table will be
mapped to an object/instance of class: the entity class.
using ASPNETCodeFirst.Models;
using Microsoft.EntityFrameworkCore;
namespace ASPNETCodeFirst.Data
{
public class OurDbContext : DbConetext
{
//non-default constructor
public OurDbContext(DbContextOptions<OurDbContext>options):base(options)
{
}
In this step we need to tell our application to use the DbContext which is inside OurDbContext
and then it has to use the SQL Server using the connection string that we defined in the
appsettings.json file. We will tell our application to do that inside program.cs file where we
configure the services that the application has to use.
Make sure to add this before calling the var app = builder.Build();
builder.Services.AddDbContext<OurDbContext>(optins=>options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
));
After configuring the program.cs file in the previous step. In this step we need to create the
database by using Entity Framework Migration. We need to run different migrations to push the
changes to the database.
add-migration AddCategroyToDatabase
The AddCategroyToDatabase above is the name for this migration. Feel free to use any
meaningful name.
Note: if you check the solution explorer you will find that a new folder called Migrations is
created.
In this folder you will find two files created. If you open the migration file you will see two
methods inside it one is called Up and the other is called Down.
One the previous migration is successful we can now push the changes to the database to
the by running the following command
update-database
Controller
After creating your model classes, you’re ready to create the controller. One option is to write the
controller code by hand, and then create all the necessary views for each controller action. After
doing that a few times, you’ll notice that it is pretty repetitive work, and you might wonder
whether you can automate the process a bit. Fortunately, you can—using a process called
scaffolding, as described in the next section.
What Is Scaffolding
Scaffolding in ASP.NET MVC can generate the boilerplate code you need for create, read,
update, and delete (CRUD) functionality in an application. The scaffolding templates can
examine the type definition for a model, and then generate a controller, the controller’s
associated views, and in some cases data access classes as well. The scaffolding knows how to
name controllers, how to name views, and what code needs to go in each component, and where
to place all these pieces in the project for the application to work.
Don’t expect scaffolding to build an entire application. Instead, expect scaffolding to release you
from the boring work of creating files in the right locations and writing 100 percent of the
application code by hand. You can tweak and edit the output of the scaffolding to make the
application your own. Scaffolding runs only when you tell it to run, so you don’t have to worry
about a code generator overwriting the changes you make to the output file.
1- go to solution explorer and right click on the controllers folder add controller
2- chose MVC Empty controller and give it a name we will name it CategroryController
3- if you open the newly created controller you will see it contains an action called Index
and if you remember our home controller also contains an action called index. So we
need to create a new view for our category controller
Create category index view
1- Right click on the index action method inside the CategoryController and chose add view
2- Chose razor view and click add.
3- From the template drop down menu select Empty (Without Model)