SlideShare una empresa de Scribd logo
CHAPTER 4
HOW TO DEVELOP A DATA-
DRIVEN MVC WEB APP
By : Eng. Mahmoud Hassouna
Email : M.hassuna2@gmail.com
How to start the Movie List app?
1. the Movie List page displays the movie data in a table
2. Above the table, the page displays a link that users can click when
they want to add a new movie.
3. Within the table, each row displays two links users can click when
they want to edit or delete an existing movie.
What happened If the user clicks the
Add New Movie link?
 The app displays the Add Movie page. This page
displays a form with text boxes that let the user enter
the name, year, and rating for a movie. In addition, it
displays a drop-down list that allows users to select a
genre for the movie.
 If the user clicks one of the Edit links in the table on the
Movie List page…
The app displays the Edit Movie page
What happened if the user clicks
one of the Delete links?
 The app displays the Delete Movie page.
 This page simply asks users to confirm that they really want to delete
the selected movie.
 If they do, they click the Delete button to delete the movie from the
database.
 If they don’t, they click the Cancel button to return the user to the
Movie List page.
The pages of the Movie List app
The folders and files of the app:
 The Solution Explorer contains:
1. Models
2. Views
3. Controllers folders
The Solution Explorer for the Movie
List app
Folders in the Movie List app
Files in the Movie List app
How to use EF Core:
 Entity Framework (EF) Core is an object-relational
mapping (ORM) framework that allows you to work with
the objects of a database in code. In the next few
figures, you’ll learn how to code classes that define the
structure of a database. Then, you’ll learn how to create
a database from this code.
How to add EF Core to your project:
 Prior to .NET Core 3.0, EF Core and the tools to work with it were
included with ASP.NET Core by default. However, with .NET Core 3.0
and later, you must manually add EF Core and the EF Core Tools to
your project. To do that with Visual Studio, you need to find and
install the correct NuGet packages.
Note:
If you try to install a version of EF Core or EF Core Tools that’s newer
than the version of .NET Core you installed, you might get errors.
How to open the NuGet Package
Manager?
Select Tools
Nuget Package
Manager
Manage Nuget
Package for
Solution
The NuGet Package Manager
How to install the EF Core and EF
Core Tools NuGet packages:
1. Click the Browse link in the upper left of the window.
2. Type “Microsoft.EntityFrameworkCore.SqlServer” in the search box.
3. Click on the appropriate package from the list that appears in the left-hand panel.
4. In the right-hand panel, check the project name, select the version that matches
the version of .NET Core you’re running, and click Install.
5. Review the Preview Changes dialog that comes up and click OK.
6. Review the License Acceptance dialog that comes up and click I Accept.
7. Type “Microsoft.EntityFrameworkCore.Tools” in the search box.
8. Repeat steps 3 through 6.
How to create a DbContext class
EF Code First:
The most common way to work with EF Core is to code your
model classes first. Then, you can use EF Core to generate a
database from those classes.
The DbContext class:
The primary class for communicating with a database.
The DbContextOptions class:
Provides configuration information to the DbContext class.
How to create a DbContext class
cont.
The DbSet class:
Represents a collection of model classes, also known as
entity classes, or domain model classes, that map to a
database table.
Three classes provided by EF Core
How to seed initial data
 One method of the DbContext class:
How to seed initial data cont.
-The MovieContext class updated to seed initial Movie data
How to add a connection string
 A connection string: is a string that specifies information
that an app needs to connect to a database or other
data source.
 To add a connection string, you can hard-code
connection strings in the code for your app, it’s generally
considered a best practice to store them in a
configuration file.
How to enable dependency injection
 Dependency injection: is a design pattern in which
the services an object needs are passed to it rather than
being hard coded as part of the object.
 Core MVC uses dependency injection to pass
DbContext objects to the controllers that need them.
A connection string in the
appsettings.json file:
Code that enables dependency
injection for DbContext objects:
How to use migrations to create the
database
 The Package Manager Console (PMC) window in Visual Studio
How to use migrations to create the
database cont.
How to open the Package Manager Console window:
Select the Tools
NutGet Package
Manager
Package Manager
Console command
How to create the Movies database based on your code files:
1. Make sure the connection string and dependency injection are set up.
2. Type “Add-Migration Initial” in the PMC at the command prompt and press Enter.
3. Type “Update-Database” at the command prompt and press Enter.
How to use migrations to create the
database cont.
 The code in the Up() method of the Initial migration file:
How to use migrations to create the
database cont.
 How to view the database once it’s created:
1. Choose the View SQL Server Object Explorer command in Visual Studio.
2. Expand the (localdb)MSSQLLocalDB node, then expand the Databases node.
3. Expand the Movies node, then expand the Tables node.
4. To view the table columns, expand a table node and then its Columns node.
5. To view the table data, right-click a table and select the ViewData command.
How to work with data
Work with Data
Select Data
Language-Intergrated
Query(LINQ)
Methods of
DbContext &
DbSet classes
Insert Update Delete
How to select Data
 Steps to using LINQ and EF Core to select data from a database:
1. build a query expression.
2. execute that query expression at the database.
How to select Data cont.
LINQ methods that build or execute a query expression
How to select Data cont.
A method of the DbSet class that gets an entity by its id
How to select Data cont.
How to select Data cont.
How to insert, update, and delete
data
 Three methods of the DbSet class
One method of the DbContext class
How to insert, update, and delete
data
How to insert, update, and delete
data
How to insert, update, and delete
data
The Movie List app
 The Home controller
 The Home/Index view
The Movie List app
 The Home controller
Figure starts by presenting the code for the Home controller of the
Movie List app. This controller starts with a private property named context of
the Movie Context type. Then, the constructor accepts a Movie Context object
and assigns it to the context property. As a result, the other methods in this class
can easily access the Movie Context object.
This constructor works because of the dependency injection code in the
Startup.cs file presented in figure 4-6. That’s because the constructor specifies
that it needs an instance of the MovieContext class. As a result, the MVC
framework creates one based on the options specified in the Startup.cs file and
passes it to that constructor.
The Index() action method of the Home controller uses the context property
to get a collection of Movie objects from the database. But first, it sorts those
objects alphabetically by movie name. Then, it passes that collection to the view.
The Movie List app
 The Home controller
The Movie List app
 The Home/Index view
This figure also presents the code for the Home/Index view of the Movie
List app. This view begins by using the @model directive to specify that the
model for this view is a collection of Movie objects because that’s what the
Index() action method of the Home controller passes to this view.
Most of the HTML in this view displays a table of movie data. Just above
the table, a link requests the Add() action method of the Movie controller. This
link allows the user to add a new movie.
Within the body of the table, an inline foreach statement loops through the
collection of Movie objects and displays each one in a row. Within that loop, the
fourth column adds links that request the Edit() and Delete() action methods of
the Movie controller for that specific movie. These links also use the asp-route-id
tag helper to pass the ID for each movie. You’ll learn more about how this tag
helper works in chapter 7. For now, all you need to know is that it appends the
MovieId value for the selected movie to the end of the URL.
The Movie List app
 The Home/Index view
The Movie List app
 The Movie controller
 Description
The Add() and Edit() action methods
both display the Movie/Edit view.
The Movie List app
 The Movie/Edit view
The Movie List app
 The Movie/Delete view
How to work with related data
 How to relate one entity to another
How to work with related data
 How to update the DbContext class and the seed data
How to work with related data
 How to use migrations to update the database
How to select related data and display it
on the Movie List page
 At this point, you’re ready to update the Movie List app so it displays this new
Genre data.
 The first example in this figure shows how to update the controller for the Movie
List page. To start, this controller adds a using directive for the EF Core
namespace. Then, the Index() action uses the Include() method of the EF Core
namespace to select the genre data related to each movie.
 The Include() method accepts a lambda expression that specifies the related entity.
Whenever necessary, you can chain the Include() method as part of a longer LINQ
query. Like the OrderBy() method, the Include() method doesn’texecute at the
database. Instead, it helps build up the query expression that theToList() method
eventually executes.
 If you only need the GenreId value, not the data for the entire entity, you don’t need
to use the Include() method. That’s because the Movie entity contains a foreign key
property named GenreId. In other words, the GenreId value is automatically
included when you select a Movie object. However, in this case, you want to get all
the Genre data, not just the GenreId value. As a result, you need to use Include().
 Once you’ve selected the related data, you use regular C# dot notation to work with
it. In the second example, for instance, the Home/Index view adds a Genre column
to the movie table. Within the foreach loop, it uses dot notation to display the Name
property of the Genre property of the Movie object.
How to select related data and display
it on the Movie List page
How to select related data and display
it on the Movie List page
 The Add() action method of the Movie controller
How to display related data on the
Add and Edit Movie pages
 The Edit() action method of the Movie controller for GET requests
 The Edit() action method of the Movie controller for POST requests
How to display related data on the
Add and Edit Movie pages
 How to make URLs lowercase with a trailing slash
How to make user-friendly URLs
By default, MVC uses the names of the controllers and their action
methods
to create the URLs of the app. By convention, these names begin with an
uppercase letter. This produces URLs that use some uppercase letters
like those
shown at the top of figure 4-19.
However, there’s also a convention that URLs should be lowercase. This
makes them easier for users to type. In addition, some developers like to
include
a trailing slash after a URL. This makes it easy for users to add text to
the end of
a URL.
Fortunately, it’s easy to make your MVC app produce URLs that are
lowercase and have a trailing slash. To do that, you just need to adjust
the
 The default URLs of an MVC app
How to make user-friendly URLs
 The same MVC pages after changing the URL configuration
How to make user-friendly URLs
 Description
• By default, MVC uses the names of the controllers and their action methods to
create the URLs of the app. By convention, these names begin with an uppercase
letter.
• It’s generally considered a good practice to use lowercase letters for URLs.
• Some developers like to include a trailing slash after each URL to make it easy for
users to type text at the end of a URL.
How to add a slug
 The Edit page with numeric ID values only in the URL
How to add a slug
 The Edit page after updating the code to add a slug to the URL
 Description
• A slug is a descriptive section at the end of a URL. You can add a
slug by adding an optional route parameter named slug to the
Startup.cs file, adding a Slug property to the entity class, and
including the Slug property on a link.
“
”
SOLVE THE EXERCISE 4-1 FROM
MURACH BOOK

Más contenido relacionado

La actualidad más candente

ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
Bagzzz
 
Oracle9i reports developer
Oracle9i reports developerOracle9i reports developer
Oracle9i reports developer
FITSFSd
 
Sqlite3 databases
Sqlite3 databasesSqlite3 databases
Sqlite3 databases
Mohamed Essam
 
As pnet
As pnetAs pnet
Programming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) EnvironmentProgramming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) Environment
Mahmoud Samir Fayed
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Bi
BiBi
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
Amit Sharma
 
Apex code-fundamentals
Apex code-fundamentalsApex code-fundamentals
Apex code-fundamentals
Amit Sharma
 
Xm Lmessagingwith Soap
Xm Lmessagingwith SoapXm Lmessagingwith Soap
Xm Lmessagingwith Soap
LiquidHub
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
vishal choudhary
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan
 
Excel
ExcelExcel
Salesforce connector Example
Salesforce connector ExampleSalesforce connector Example
Salesforce connector Example
prudhvivreddy
 
Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...
Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...
Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...
GEBS Reporting
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
Amit Sharma
 

La actualidad más candente (17)

ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
Oracle9i reports developer
Oracle9i reports developerOracle9i reports developer
Oracle9i reports developer
 
Sqlite3 databases
Sqlite3 databasesSqlite3 databases
Sqlite3 databases
 
As pnet
As pnetAs pnet
As pnet
 
Programming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) EnvironmentProgramming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) Environment
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Bi
BiBi
Bi
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
 
Apex code-fundamentals
Apex code-fundamentalsApex code-fundamentals
Apex code-fundamentals
 
Xm Lmessagingwith Soap
Xm Lmessagingwith SoapXm Lmessagingwith Soap
Xm Lmessagingwith Soap
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
 
Excel
ExcelExcel
Excel
 
Salesforce connector Example
Salesforce connector ExampleSalesforce connector Example
Salesforce connector Example
 
Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...
Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...
Generate Excel documents with Rational Publishing Engine 1.1.2 and Reporting ...
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
 

Similar a Murach': HOW TO DEVELOP A DATA DRIVEN MVC WEB

Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
Metamorphosis from Forms to Java: A technical lead's perspective, part II
Metamorphosis from Forms to Java:  A technical lead's perspective, part IIMetamorphosis from Forms to Java:  A technical lead's perspective, part II
Metamorphosis from Forms to Java: A technical lead's perspective, part II
Michael Fons
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
Akhil Mittal
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
16 asp.net session23
16 asp.net session2316 asp.net session23
16 asp.net session23
Vivek chan
 
NET_Training.pptx
NET_Training.pptxNET_Training.pptx
NET_Training.pptx
ssuserc28c7c1
 
Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basic
Techglyphs
 
3 tier architecture in asp.net
3 tier architecture in asp.net3 tier architecture in asp.net
3 tier architecture in asp.net
Ravi Bansal
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Akhil Mittal
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
DEVICE CHANNELS
DEVICE CHANNELSDEVICE CHANNELS
DEVICE CHANNELS
Assaf Biton
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
Rich Helton
 
HP ArcSight Asset Model Import FlexConnector Developer's Guide
HP ArcSight Asset Model Import FlexConnector Developer's GuideHP ArcSight Asset Model Import FlexConnector Developer's Guide
HP ArcSight Asset Model Import FlexConnector Developer's Guide
Protect724tk
 
How to broadcast a b ex report through e
How to broadcast a b ex report through eHow to broadcast a b ex report through e
How to broadcast a b ex report through e
Zaynab Fadlallah
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
FaRid Adwa
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Web-Dev Portfolio
Web-Dev PortfolioWeb-Dev Portfolio
Web-Dev Portfolio
nwbgh
 
Components lab
Components labComponents lab
Components lab
Joanne Scouler
 
Ef code first
Ef code firstEf code first
Ef code first
ZealousysDev
 

Similar a Murach': HOW TO DEVELOP A DATA DRIVEN MVC WEB (20)

Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Metamorphosis from Forms to Java: A technical lead's perspective, part II
Metamorphosis from Forms to Java:  A technical lead's perspective, part IIMetamorphosis from Forms to Java:  A technical lead's perspective, part II
Metamorphosis from Forms to Java: A technical lead's perspective, part II
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
16 asp.net session23
16 asp.net session2316 asp.net session23
16 asp.net session23
 
NET_Training.pptx
NET_Training.pptxNET_Training.pptx
NET_Training.pptx
 
Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basic
 
3 tier architecture in asp.net
3 tier architecture in asp.net3 tier architecture in asp.net
3 tier architecture in asp.net
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
 
DEVICE CHANNELS
DEVICE CHANNELSDEVICE CHANNELS
DEVICE CHANNELS
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
HP ArcSight Asset Model Import FlexConnector Developer's Guide
HP ArcSight Asset Model Import FlexConnector Developer's GuideHP ArcSight Asset Model Import FlexConnector Developer's Guide
HP ArcSight Asset Model Import FlexConnector Developer's Guide
 
How to broadcast a b ex report through e
How to broadcast a b ex report through eHow to broadcast a b ex report through e
How to broadcast a b ex report through e
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Web-Dev Portfolio
Web-Dev PortfolioWeb-Dev Portfolio
Web-Dev Portfolio
 
Components lab
Components labComponents lab
Components lab
 
Ef code first
Ef code firstEf code first
Ef code first
 

Último

Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
RidwanHassanYusuf
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
IsmaelVazquez38
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
National Information Standards Organization (NISO)
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
khuleseema60
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
Prof. Dr. K. Adisesha
 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
nitinpv4ai
 

Último (20)

Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
 

Murach': HOW TO DEVELOP A DATA DRIVEN MVC WEB

  • 1. CHAPTER 4 HOW TO DEVELOP A DATA- DRIVEN MVC WEB APP By : Eng. Mahmoud Hassouna Email : M.hassuna2@gmail.com
  • 2. How to start the Movie List app? 1. the Movie List page displays the movie data in a table 2. Above the table, the page displays a link that users can click when they want to add a new movie. 3. Within the table, each row displays two links users can click when they want to edit or delete an existing movie.
  • 3. What happened If the user clicks the Add New Movie link?  The app displays the Add Movie page. This page displays a form with text boxes that let the user enter the name, year, and rating for a movie. In addition, it displays a drop-down list that allows users to select a genre for the movie.  If the user clicks one of the Edit links in the table on the Movie List page… The app displays the Edit Movie page
  • 4. What happened if the user clicks one of the Delete links?  The app displays the Delete Movie page.  This page simply asks users to confirm that they really want to delete the selected movie.  If they do, they click the Delete button to delete the movie from the database.  If they don’t, they click the Cancel button to return the user to the Movie List page.
  • 5. The pages of the Movie List app
  • 6. The folders and files of the app:  The Solution Explorer contains: 1. Models 2. Views 3. Controllers folders
  • 7. The Solution Explorer for the Movie List app
  • 8. Folders in the Movie List app
  • 9. Files in the Movie List app
  • 10. How to use EF Core:  Entity Framework (EF) Core is an object-relational mapping (ORM) framework that allows you to work with the objects of a database in code. In the next few figures, you’ll learn how to code classes that define the structure of a database. Then, you’ll learn how to create a database from this code.
  • 11. How to add EF Core to your project:  Prior to .NET Core 3.0, EF Core and the tools to work with it were included with ASP.NET Core by default. However, with .NET Core 3.0 and later, you must manually add EF Core and the EF Core Tools to your project. To do that with Visual Studio, you need to find and install the correct NuGet packages. Note: If you try to install a version of EF Core or EF Core Tools that’s newer than the version of .NET Core you installed, you might get errors.
  • 12. How to open the NuGet Package Manager? Select Tools Nuget Package Manager Manage Nuget Package for Solution
  • 13. The NuGet Package Manager
  • 14. How to install the EF Core and EF Core Tools NuGet packages: 1. Click the Browse link in the upper left of the window. 2. Type “Microsoft.EntityFrameworkCore.SqlServer” in the search box. 3. Click on the appropriate package from the list that appears in the left-hand panel. 4. In the right-hand panel, check the project name, select the version that matches the version of .NET Core you’re running, and click Install. 5. Review the Preview Changes dialog that comes up and click OK. 6. Review the License Acceptance dialog that comes up and click I Accept. 7. Type “Microsoft.EntityFrameworkCore.Tools” in the search box. 8. Repeat steps 3 through 6.
  • 15. How to create a DbContext class EF Code First: The most common way to work with EF Core is to code your model classes first. Then, you can use EF Core to generate a database from those classes. The DbContext class: The primary class for communicating with a database. The DbContextOptions class: Provides configuration information to the DbContext class.
  • 16. How to create a DbContext class cont. The DbSet class: Represents a collection of model classes, also known as entity classes, or domain model classes, that map to a database table.
  • 18.
  • 19.
  • 20. How to seed initial data  One method of the DbContext class:
  • 21. How to seed initial data cont. -The MovieContext class updated to seed initial Movie data
  • 22. How to add a connection string  A connection string: is a string that specifies information that an app needs to connect to a database or other data source.  To add a connection string, you can hard-code connection strings in the code for your app, it’s generally considered a best practice to store them in a configuration file.
  • 23. How to enable dependency injection  Dependency injection: is a design pattern in which the services an object needs are passed to it rather than being hard coded as part of the object.  Core MVC uses dependency injection to pass DbContext objects to the controllers that need them.
  • 24. A connection string in the appsettings.json file:
  • 25. Code that enables dependency injection for DbContext objects:
  • 26. How to use migrations to create the database  The Package Manager Console (PMC) window in Visual Studio
  • 27. How to use migrations to create the database cont. How to open the Package Manager Console window: Select the Tools NutGet Package Manager Package Manager Console command How to create the Movies database based on your code files: 1. Make sure the connection string and dependency injection are set up. 2. Type “Add-Migration Initial” in the PMC at the command prompt and press Enter. 3. Type “Update-Database” at the command prompt and press Enter.
  • 28. How to use migrations to create the database cont.  The code in the Up() method of the Initial migration file:
  • 29. How to use migrations to create the database cont.  How to view the database once it’s created: 1. Choose the View SQL Server Object Explorer command in Visual Studio. 2. Expand the (localdb)MSSQLLocalDB node, then expand the Databases node. 3. Expand the Movies node, then expand the Tables node. 4. To view the table columns, expand a table node and then its Columns node. 5. To view the table data, right-click a table and select the ViewData command.
  • 30. How to work with data Work with Data Select Data Language-Intergrated Query(LINQ) Methods of DbContext & DbSet classes Insert Update Delete
  • 31. How to select Data  Steps to using LINQ and EF Core to select data from a database: 1. build a query expression. 2. execute that query expression at the database.
  • 32. How to select Data cont. LINQ methods that build or execute a query expression
  • 33. How to select Data cont. A method of the DbSet class that gets an entity by its id
  • 34. How to select Data cont.
  • 35. How to select Data cont.
  • 36. How to insert, update, and delete data  Three methods of the DbSet class One method of the DbContext class
  • 37. How to insert, update, and delete data
  • 38. How to insert, update, and delete data
  • 39. How to insert, update, and delete data
  • 40. The Movie List app  The Home controller  The Home/Index view
  • 41. The Movie List app  The Home controller Figure starts by presenting the code for the Home controller of the Movie List app. This controller starts with a private property named context of the Movie Context type. Then, the constructor accepts a Movie Context object and assigns it to the context property. As a result, the other methods in this class can easily access the Movie Context object. This constructor works because of the dependency injection code in the Startup.cs file presented in figure 4-6. That’s because the constructor specifies that it needs an instance of the MovieContext class. As a result, the MVC framework creates one based on the options specified in the Startup.cs file and passes it to that constructor. The Index() action method of the Home controller uses the context property to get a collection of Movie objects from the database. But first, it sorts those objects alphabetically by movie name. Then, it passes that collection to the view.
  • 42. The Movie List app  The Home controller
  • 43. The Movie List app  The Home/Index view This figure also presents the code for the Home/Index view of the Movie List app. This view begins by using the @model directive to specify that the model for this view is a collection of Movie objects because that’s what the Index() action method of the Home controller passes to this view. Most of the HTML in this view displays a table of movie data. Just above the table, a link requests the Add() action method of the Movie controller. This link allows the user to add a new movie. Within the body of the table, an inline foreach statement loops through the collection of Movie objects and displays each one in a row. Within that loop, the fourth column adds links that request the Edit() and Delete() action methods of the Movie controller for that specific movie. These links also use the asp-route-id tag helper to pass the ID for each movie. You’ll learn more about how this tag helper works in chapter 7. For now, all you need to know is that it appends the MovieId value for the selected movie to the end of the URL.
  • 44. The Movie List app  The Home/Index view
  • 45. The Movie List app  The Movie controller  Description The Add() and Edit() action methods both display the Movie/Edit view.
  • 46. The Movie List app  The Movie/Edit view
  • 47. The Movie List app  The Movie/Delete view
  • 48. How to work with related data  How to relate one entity to another
  • 49. How to work with related data  How to update the DbContext class and the seed data
  • 50. How to work with related data  How to use migrations to update the database
  • 51. How to select related data and display it on the Movie List page  At this point, you’re ready to update the Movie List app so it displays this new Genre data.  The first example in this figure shows how to update the controller for the Movie List page. To start, this controller adds a using directive for the EF Core namespace. Then, the Index() action uses the Include() method of the EF Core namespace to select the genre data related to each movie.  The Include() method accepts a lambda expression that specifies the related entity. Whenever necessary, you can chain the Include() method as part of a longer LINQ query. Like the OrderBy() method, the Include() method doesn’texecute at the database. Instead, it helps build up the query expression that theToList() method eventually executes.
  • 52.  If you only need the GenreId value, not the data for the entire entity, you don’t need to use the Include() method. That’s because the Movie entity contains a foreign key property named GenreId. In other words, the GenreId value is automatically included when you select a Movie object. However, in this case, you want to get all the Genre data, not just the GenreId value. As a result, you need to use Include().  Once you’ve selected the related data, you use regular C# dot notation to work with it. In the second example, for instance, the Home/Index view adds a Genre column to the movie table. Within the foreach loop, it uses dot notation to display the Name property of the Genre property of the Movie object. How to select related data and display it on the Movie List page
  • 53. How to select related data and display it on the Movie List page
  • 54.  The Add() action method of the Movie controller How to display related data on the Add and Edit Movie pages  The Edit() action method of the Movie controller for GET requests
  • 55.  The Edit() action method of the Movie controller for POST requests How to display related data on the Add and Edit Movie pages
  • 56.  How to make URLs lowercase with a trailing slash How to make user-friendly URLs By default, MVC uses the names of the controllers and their action methods to create the URLs of the app. By convention, these names begin with an uppercase letter. This produces URLs that use some uppercase letters like those shown at the top of figure 4-19. However, there’s also a convention that URLs should be lowercase. This makes them easier for users to type. In addition, some developers like to include a trailing slash after a URL. This makes it easy for users to add text to the end of a URL. Fortunately, it’s easy to make your MVC app produce URLs that are lowercase and have a trailing slash. To do that, you just need to adjust the
  • 57.  The default URLs of an MVC app How to make user-friendly URLs
  • 58.  The same MVC pages after changing the URL configuration How to make user-friendly URLs  Description • By default, MVC uses the names of the controllers and their action methods to create the URLs of the app. By convention, these names begin with an uppercase letter. • It’s generally considered a good practice to use lowercase letters for URLs. • Some developers like to include a trailing slash after each URL to make it easy for users to type text at the end of a URL.
  • 59. How to add a slug  The Edit page with numeric ID values only in the URL
  • 60. How to add a slug  The Edit page after updating the code to add a slug to the URL  Description • A slug is a descriptive section at the end of a URL. You can add a slug by adding an optional route parameter named slug to the Startup.cs file, adding a Slug property to the entity class, and including the Slug property on a link.
  • 61. “ ” SOLVE THE EXERCISE 4-1 FROM MURACH BOOK