0% found this document useful (0 votes)
37 views

L2 ASP - NET MVC Code First Approach - 075015

The document discusses code first approach in ASP.NET MVC using Entity Framework Core. It involves creating model classes first, then generating the database based on those classes. The key steps are: 1) Creating model classes and adding data annotations. 2) Adding a connection string. 3) Creating a DbContext class derived from Microsoft.EntityFrameworkCore.DbContext. 4) Setting up migrations to generate the database from the models. The code first approach allows developing the application code and database together from the start.

Uploaded by

m.a.770861365
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

L2 ASP - NET MVC Code First Approach - 075015

The document discusses code first approach in ASP.NET MVC using Entity Framework Core. It involves creating model classes first, then generating the database based on those classes. The key steps are: 1) Creating model classes and adding data annotations. 2) Adding a connection string. 3) Creating a DbContext class derived from Microsoft.EntityFrameworkCore.DbContext. 4) Setting up migrations to generate the database from the models. The code first approach allows developing the application code and database together from the start.

Uploaded by

m.a.770861365
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Advanced Software Design and Development

Lecture 2: ASP.NET MVC Code First Approach

What is code first approach?


Code first is a technique where we start by writing our .NET Code first, then, based on the
written code the database will be generated .It helps us to create a database, migrate and maintain
the database and its tables from the code. This approach is helpful when you don’t have a
database ready and you want to start working with new fresh project and want to create a
database and maintain the database directly from your code.

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.

Object Relational Mapper (ORM)

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.

Code First Conventions

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.

Step3: Add the connection string to appsettings.json file.

Step4: Add DbContext class.

Step5: Setup Program.cs to use DbContext.

Step6: Create database table by using Entity Framework migrations.

We will go through these steps in details as following.

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.

Relational database Model in MVC


Concept Example Concept Example
Table Student table Class Class Student{}
Columns studentId Class properties int studentId
Constraints Primary key Data annotations [key]

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)).

Name the application as ASPNETCodeFirst


Install the following NuGet packages

 Microsoft.EntityFrameworkCore.Tools;[To enable migrations]


 Microsoft.EntityFrameworkCore.Design;
 Microsoft.EntityFrameworkCore.SqlServer;

Step2: Create the model class and add the required data annotations

- Right click on the Models folder  Add  Class


- Name the class as Category.cs and add the properties for this class. Make sure each
model class contains one property that
 Has the name Id, or
 Has the name [classname]Id, or
 Has the [Key] attribute.

Such a property will be mapped as the primary key of the corresponding table, to uniquely
identify each row in the table.

public class Category


{
public int CategoryId { get; set; }
public string CategoryName { get; set; } = string.Empty;
public string CategoryDescription { get; set; } = string.Empty;
public DateTime CategoryCreatedDate { get; set; }= DateTime.Now;
}

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.

Attribute Description Example


To define the property as a primary key if the model
Key [key]
is not having property with the name Id.
This attribute ensures that the value is not empty or a
string consisting only of spaces. If you want to treat
Required [Required]
whitespace as valid, use
[Required(AllowEmptyStrings = true)].
This attribute ensures that a numeric value (or any
property type that implements IComparable) is not
Range [Range(10, 20)]
outside the range of specified minimum and
maximum values.
This attribute ensures that a string value is no longer
than a specified maximum length. You can also
StringLength [StringLength(10)]
specify a minimum length:
[StringLength(10, MinimumLength=2)].
EmailAddress checks that the property has a valid email format. [EmailAddress]
checks that the property has a valid telephone number
Phone [Phone]
format.
Url checks that the property has a proper URL format. [Url]

Note1: you should use the name space called “System.ComponentModel.DataAnnotations;” in


order to be able to use these attributes.

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":{

"DefaultConnection":"Server = (localdb)\\MSSQLLocalDB; Database = CFDB; Trusted_Connection = True;"

In the above we have the following:

- ConnectionStrings: is the block name.


- DefaultConnection: is the name of the connection string.
- Server: to specify the server name which is :"(localdb)\\MSSQLLocalDB
- Database: to specify the name of the database that we want to create which we named it
as CFDB
- Trusted_Connection: for authentication

Step4: The DbContext and DbSet Classes


There are two main classes we’ll make of when working with Entity Framework Core.
When you’re using EF’s code-first approach, the gateway to the database is a class derived from
EF’s DbContext class. The derived class has one or more properties of type DbSet<T>, where
each T represents the type of object you want to persist. You can think of a DbSet as a special,
data-aware generic list that knows how to load and save data from its parent context.

DbContext class

Has many important responsibilities, including

– Database connections (open, close, and manage connections to a database);

– 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);

– Data mapping (it maps properties from entities to columns in tables);


– Transaction management (when SaveChanges is called, a transaction is created for all
pending changes. If an error/exception occurs when the changes are applied to the
database, they are all rolled back).

DbSet <TEntity> class

– 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.

Create a Class Derived from DbContext

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;

public class OurDbContext : DbContext


{
}

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.

The class after adding the DbSet will be as following:

using ASPNETCodeFirst.Models;
using Microsoft.EntityFrameworkCore;
namespace ASPNETCodeFirst.Data
{
public class OurDbContext : DbConetext
{
//non-default constructor
public OurDbContext(DbContextOptions<OurDbContext>options):base(options)
{
}

// Dbset to be mapped to the database table


public DbSet<Category> Categories { get; set; }
}
}

Step5: Setup Program.cs to use DbContext.

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")
));

Step6: Create database table by using Entity Framework migrations.

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.

In visual studio go to tools  NuGet Package Manager  Package Manager Console

Then add the following migrations

 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.

Create category controller

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)

You might also like