1 ASP - Net Core MVC, Web API, Ef, Repo
1 ASP - Net Core MVC, Web API, Ef, Repo
NET Core
ASP.NET Core MVC, Web API, Entity Framework
Content
• .NET Core • Repository pattern
• .NET Core CLI • Entity framework Core
• ASP.NET MVC Core • Web API
• Model, View, Controller
• Action Methods
• Routing
• Middleware
• Tag helpers
• Dependency injection
• Security
2
Pre test
https://www.surveymonkey.com/r/PX8BL3F
4
Required Software
• Windows 10 (Linux, Mac)
• Go to http://dot.net OR https://www.microsoft.com/net and
download .NET Core SDK
• Visual Studio
• Edition, per requirement: https://www.visualstudio.com/
• Code: https://code.visualstudio.com/
5
Why .NET Core?
• Cross-platform development framework
• Need for a highly modular framework
• Need for high performance and scalable systems
• Need for pure Open-Source framework with direct support from
community
• Need for framework with frequent updates
6
.NET Core version history
Version Release date Released with
.NET Core 1.0 2016-06-27 Visual Studio 2015 Update 3
.NET Core 1.1 2016-11-16 Visual Studio 2017 Version 15.0
.NET Core 2.0 2017-08-14 Visual Studio 2017 Version 15.3
.NET Core 2.1 2018-05-30 Visual Studio 2017 Version 15.7
.NET Core 2.2 2018-12-04 Visual Studio 2019 Version 16.0
.NET Core 3.0 2019-09-23 Visual Studio 2019 Version 16.3
.NET Core 3.1 2019-12-03 Visual Studio 2019 Version 16.4
2020-11
.NET 5 (projected)
7
.NET Core Components
• .NET runtime (CoreCLR), which provides a type system, assembly
loading, a garbage collector, native interop and other basic services.
The .NET Core runtime includes the same GC and JIT (RyuJIT), but
doesn’t include features like Application Domains or Code Access
Security.
• Framework libraries (CoreLibrary), factored base library (removal of
dependencies) to provide primitive data types, app composition types
and fundamental utilities.
• SDK tools and compilers (CoreSDK) contains CLI tools and 'dotnet' app
host, which is used to launch .NET Core apps
8
.NET Framework vs Core
Compilation Process
9
.NET Core Vs.NET Framework
Criteria .NET Core .NET Framework
App-models/ It supports Console, Library, Web apps and Web It supports all work loads including Win
Work loads API across platforms forms, WPF, WCF but only in Windows
machines.
API It has fewer API (implemented by .NET Standard) It has rich set of API for windows platforms
although list is growing in each versions
Open Source .NET Core is fully open source only a read-only subset of the .NET
Framework is open source.
11
.NET Core CLI
• Command Line Interface
• Commands
https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet?tabs=netcore21#
dotnet-commands
13
.NET Core CLI
• Create new project with dotnet new
• Edit packages in project.json
• Write some C#
14
LAB
• “Hello CGI” console application
15
ASP.NET MVC
Build web app
16
MVC
• Architectural pattern
• MVC pattern is from SmallTalk team, first academic paper is from year
1979
• By the original definition
• MODEL – business info and logic
• VIEW – visual (partial) representation of model
• CONTROLLER – middle part in between user and system
17
MVC
• Model
• Business logic and its persistence
• View
• Template for displaying data
• Controller
• Communication between Model, View and end-user
• ViewModel
• Models used for supplying views with complex (strongly typed) data
18
Routing
https://localhost/Employees/Index
Controller
Action
{Controller}/{Action}/{id?}
19
MVC Web App Basics
Updates
User Requests
View
Controller
Updates
Model View
Model Gets
Data
20
Server Side (IIS, Kestrel)
Request Routing
{controller}/
{action}/{id?}
Controller
Action method
Response (HTML)
View
21
ASP.NET Core MVC Framework
• Controllers – light and easy, async
• Routing – conventional and by attributes
• Models – enhanced model binding
• Built-in dependency resolver (with lifetime support)
• Views – good old Razor (HTML Helpers & tag helpers)
• Web API – merged with MVC
• Identity – built-in authentication & authorization support
22
The Road to ASP.NET
Core 3.0
2018 2019
2016
2002 ASP.NET Core ASP.NET Core 3.1
ASP.NET Core 1.0
ASP.NET WebForms 2.1 & 2.2
23
LAB - Employee Management
System
• Create ASP.NET Web app – Ems_Mvc_InMemory
• Use ASP.NET MVC template
25
Site Configuration
26
Project Structure
27
Program.c
s
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
28
Program.c
s
29
Startup.cs
30
public void ConfigureServices(IServiceCollection services)
{
//register services here through Dependency Injection
ConfigureServices
Method
31
public void ConfigureServices(IServiceCollection services)
{
//register framework services
services.AddControllersWithViews();
//register our own services (more
later)
}
ConfigureServices
Method
32
Configure
Method
33
Middleware Request
Pipeline
Request
34
Configure
Method
35
Ordering Middleware
Components
Request
Configure method
Startup class
Pipeline is created
37
ASP.NET Core request processing
38
ASP.NET MVC request processing
39
Controller & Action
Methods
ASP.NET Core MVC
40
MVC - Controller
• Controller – define and group actions (or action method) for servicing
incoming web requests.
• Can be any class that ends in “Controller” or inherits from class that
ends with “Controller”
• Convention is (but are not required)
• Controllers are located in “Controllers” folder
• Controllers inherit from Microsoft.AspNetCore.Mvc.Controller
41
MVC - Controller
• Action Methods can return various responses
• View
• Return View(viewModel);
• HTTP Status Code
• Return BadRequest();
• Formatted Response
• Return Json(someObject);
• Content negotiated response
• Return Ok();
• Redirect
• Return RedirectToAction(“Complete”, viewModel);
42
Action Method
• Restrictions
• Action method must be public. It cannot be private or protected
• Action method cannot be overloaded
• Action method cannot be a static method.
43
Action Method
• Index action method of StudentController
44
Default Action Method
• Every controller can have default action method as per configured
route in RouteConfig class Middleware.
• By default, Index is a default action method for any controller, as per
configured default route
endpoints.MapControllerRoute(
name: "default",
pattern:
"{controller=Employees}/{action=Index}/{id?}");
45
ActionResult
Action Result Helper Method Description
ViewResult View Renders a view as a Web page.
RedirectToAction
RedirectToRouteResult RedirectToRoute Redirects to another action method.
[HttpDelete]
public ActionResult Delete(int id)
{
// delete student from the database whose id matches with specified id
return RedirectToAction("Index");
}
48
LAB
• Create Employee Model • Add EmployeesController
• Id • List
• Name • Add Employee
• DateOfJoining • Validations?
• Email
• Phone
• Gender
49
Adding Validation
50
MVC – Model validation
• Validation attributes mostly in
System.ComponentModel.DataAnnotations
• [Required], [MaxLength()], etc.
• Model validation occurs prior to action invocation
• Actions has to inspect ModelState.IsValid (server side validation)
• If needed, call TryValidateModel(someModel) again
51
if (ModelState.IsValid)
{
_orderRepository.CreateOrder(order);
return RedirectToAction("CheckoutComplete");
}
else
{
return View();
}
Model
Validation
52
Validation
Constraints,
Attributes on
required, regex Custom attributes
the model
patterns…
classes
54
Required
StringLength
Range
Validatio RegularExpressio
n n DataType
Attribute - Phone
s - Email
- Url
55
Adding Validation Attributes
56
<form asp-action="Checkout" method="post">
<div asp-validation-summary="All" class="text-danger">
</div>
</form>
Validation Summary
57
Custom Validation 1
• Implement IValidatableObject on model
58
Custom Validation 2
• Inherit from ValidationAttribute
59
Custom Validation
• ValidationAttribute
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation
?view=aspnetcore-3.0#custom-client-side-validation
60
Revision
• .NET Core • ASP .NET Core MVC
• .NET Core CLI • MVC
• Request, Response
• Middleware
• Registering dependent services
• Action Method
• Tag Helper
• Data Annotations
• Custom validation
61
LAB: Employee Management
System
• Employee Model • Employees Controller
• Id • List
• Name • Create
• DateOfJoining • Client side validation
• Email • Server side validation
• Phone • Edit
• Gender • Client side validation
• Add validations to model • Server side validation
• Business rules • Delete
• Date of joining should be in the past • Details
• Gender should be
Male/Female/TransGender
62
Server Side (IIS, Kestrel)
Request
Middleware
Routing
{controller}/
{action}/{id?}
Controller
Action method
Model
Response (HTML)
View
63
ActionVerb (Get, Post,…)
64
Action Selector: ActionVerb
65
Action Selector: ActionVerb
Http method Usage
To retrieve the information from the server. Parameters will be
GET
appended in the query string.
POST To create a new resource.
PUT To update an existing resource.
HEAD Identical to GET except that server do not return message body.
OPTIONS method represents a request for information about the
OPTIONS
communication options supported by web server.
DELETE To delete an existing resource.
PATCH To full or partial update the resource.
66
Action Selector: ActionVerb
• Apply multiple HTTP verbs using AcceptVerbs attribute
• GetAndPostAction method supports both, GET and POST ActionVerbs
in the following example:
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
return RedirectToAction("Index");
}
67
Tag helpers
ASP.NET MVC - Views
68
ASP.NET Core - Views
• In the Model-View-Controller (MVC) pattern, the view encapsulates
the presentation details of the user's interaction with the app.
• Views are HTML templates with embedded code that generate
content to send to the client.
• Views use Razor syntax, which allows code to interact with HTML with
minimal code
69
Views
• .cshtml extension
• Are located in– Views folder
• Typically, each controller has its own folder within Views folder
• Typically, every action has its own view
\Views\<ControllerName>\<ActionName>.cshtml
• Shared views are in folder \Views\Shared
• In addition to action specific views there are
partial views, layouts, special view files, ….
70
Views – Tag Helpers
• Tag Helpers enable server-side code to participate in creating and rendering
HTML elements in Razor files.
• Built-in Tag Helpers for common tasks - such as creating forms, links, loading
assets and more
• Are authored in C#, and they target HTML elements based on element name,
attribute name, or parent tag
• Do not replace Html helpers – there is not a Tag helper for every Html helper
• Custom tag helpers can be created
71
Tag Helpers
• Consider Student Model
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
• Razor markup in Create View
<label asp-for="FirstName"></label>
72
Views – Tag Helpers - <form>
<form
asp-controller="Account"
• Asp-action asp-action="Login"
asp-route-
• Asp-all-route-data returnurl="@ViewData["ReturnUrl"]"
• Asp-antiforgery method="post"
class="form-horizontal">
• Asp-area <form method="post" class="form-
horizontal"
• Asp-controller action="/Account/Login">
• Asp-fragment
• Asp-route
• Asp-route-<parameter name>
73
Views – Tag Helpers - <div>
• Asp-validation-summary – display validation summary in this div
• ValidationSummary
All – property and model
ModelOnly – only model
None - none
74
Views – Tag Helpers - <input>
• Input type is set based on .NET type
.NET type Input Type
Bool type=”checkbox”
String type=”text”
DateTime type=”datetime”
Byte type=”number”
Int type=”number”
75
Views – Tag Helpers - <input>
• Or use data annotations
Attribute Input Type
[EmailAddress] type=”email”
[Url] type=”url”
[HiddenInput] type=”hidden”
[Phone] type=”tel”
[DataType(DataType.Password)] type=”password”
[DataType(DataType.Date)] type=”date”
[DataType(DataType.Time)] type=”time”
76
Views – Tag Helpers - <span>
• Asp-validation-for
Display validation error (if there is one for this model property) in this
span
<span asp-validation-for="LastName"
class="text-danger"></span>
77
Views – Tag Helpers - <label>
• Asp-for
Generate label for this model property
78
Views – Tag Helpers - <select>,
option group <optgroup>
• Asp-for
specifies the model property
• Asp-items
specifies option elements (List<SelectListItem>)
<select asp-for="Country" asp-
items="Model.Countries"></select>
• You can generate option list from enums
<select asp-for="EnumCountry"
asp-
items="Html.GetEnumSelectList<CountryEnum>()">
79
Views – Tag Helpers - Collections
public class ToDoItem
{
public string Name { get;
set; }
public bool IsDone { get;
set; }
@model List<ToDoItem>
}
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
<label asp-for="@Model[i].Name"></label>
</td>
<td>
<input asp-for="@Model[i].IsDone" />
</td>
</tr>
}
80
Views – Tag Helpers - <a>
• Asp-action, Asp-all-route-data, Asp-area, Asp-controller, Asp-
fragment
Asp-route, Asp-route-<parameter name>
• Asp-host
Specify host to use in generated link (default is relative to current
host)
• Asp-protocol
Specify protocol to use (default is current protocol)
81
Tag Helpers and HTML Helpers
• Tag Helpers attach to HTML elements in Razor views, while HTML
Helpers are invoked as methods interspersed with HTML in Razor
views
@Html.Label("FirstName", "First Name:", new { @class = "captio
n" })
• Intellisense doesn’t help
• To a front-end designer (someone familiar with HTML/CSS/JavaScript
and other client technologies but not familiar with C# and Razor),
most of the line is foreign. The entire line must be authored with no
help from IntelliSense.
82
Tag Helpers and HTML Helpers
• Using the LabelTagHelper, the same markup can be written as:
83
Tag Helpers and HTML Helpers
• The markup is much cleaner and easier to read, edit, and maintain
than the HTML Helpers approach.
• C# code is reduced to the minimum that the server needs to know
about.
• Visual Studio editor displays markup targeted by a Tag Helper in a
distinctive font.
• Visual Studio editor helps you write all of the markup in the Tag
Helper, while Visual Studio provides no help for most of the code in
the HTML Helpers approach
84
Custom Tag Helper
• Create tag helper to repeat HTML element n times
• Create class and inherit from TagHelper
• Override members
• _ViewImports.cshtml file
• add a line to register your Tag Helper: @addTagHelper *, <Assembly Name>
• Go to view and add custom tag helper
85
LAB: Find employee by Id
• Add method GetEmployeeById
• Take employee id from user
• Perform validation
• Client side
• Server side
• Create appropriate view
86
Assignment: EMS - Search
• Search by Gender : radio buttons
• Search by Job Title : select list
87
Assignment: Student Mgmt System
• Student model with validations • Create a global list of students
• Id • Add 2 student info
• Name
• DateOfBirth • Student Controller Action
• Gender methods
• Email • List
• Phone • Create
• Class
• Edit
• Business rules
• Delete
• Date of birth should be in the past
• Phone number should be 10 digit Indian • Details
mobile number • GetStudentsByClass
• Class (1 to 10)
88
Passing data to View
• Model
• ViewBag
• ViewData
• TempData
• ViewModel
89
ViewBag
• dynamic type
• ViewBag transfers data from the controller to the view, ideally
temporary data which in not included in a model.
• You can assign any number of propertes and values to ViewBag
• The ViewBag's life only lasts during the current http request. ViewBag
values will be null if redirection occurs.
• ViewBag is actually a wrapper around ViewData
90
ViewData
• Dictionary type
• ViewData transfers data from the Controller to View, not vice-versa.
• ViewData's life only lasts during current http request. ViewData values
will be cleared if redirection occurs.
• ViewData value must be type cast before use.
91
TempData
• dictionary type
• TempData can be used to store data between two consecutive requests.
TempData values will be retained during redirection.
• TempData internaly use Session to store the data. So think of it as a short
lived session.
• TempData value must be type cast before use. Check for null values to
avoid runtime error.
• TempData can be used to store only one time messages like error
messages, validation messages.
• Call TempData.Keep() to keep all the values of TempData in a third request.
92
TempData
93
Repository pattern
94
Repository pattern
• Domain Driven Design
• Repositories are classes or components that encapsulate the logic
required to access data sources (DAL)
• They centralize common data access functionality, providing better
maintainability and decoupling the infrastructure or technology
used to access databases from the domain model layer
• Mediates between the domain and data mapping layers using a
collection-like interface for accessing domain objects
Martin Fowler, https://martinfowler.com/eaaCatalog/repository.html
95
Server Side (IIS, Kestrel)
Repository
Request
Middleware Interface
Class
Routing
{controller}/
{action}/{id?} Method
Controller
Action method
Calls
Access data
Model
97
public interface IEmployeeRepository
{
IEnumerable<Employee> GetAllEmployees();
Employee GetEmployeeById(int employeeId);
}
98
LAB: Repository
• Create ASP.NET Core MVC project
• Employee Model
• Employee controller
• Add Folder Repositories
• Generic Repository interface
99
Repository Implementation
101
Registering the Repository
Services
Repository “Consumer” class
Startup
class
102
public void ConfigureServices(IServiceCollection services)
{
//register framework services
services.AddMvc();
103
Registration options
104
LAB: Repository
• Create ASP.NET Core MVC project
• Employee Model
• Validations
• Employee controller
• Add Folder Repositories
• Generic Repository interface
• Employee Repository class
• Register repository as dependent service (in Startup
ConfigureServices)
105
Revision
• ASP .NET Core MVC • Repository pattern
• MVC • Entity Framework
• Request, Response • Database First
• Middleware • Code First
• Registering dependent services
• Action Method
• Tag Helper
• Data Annotations
• Custom validation
• Repository Pattern
106
Server Side (IIS, Kestrel)
Repository
Request
Middleware Interface
Class
Routing
{controller}/
{action}/{id?} Method
Controller
Action method
Calls
Access data
Model
107
Registered service lifetime
• Built-in IoC container manages the lifetime of a registered
service type. It automatically disposes a service instance
based on the specified lifetime.
• The built-in IoC container supports three kinds of lifetimes:
– Singleton: A single instance of a service is created and shared
throughout the application's lifetime
– Transient: a new instance of the service type created every time
you ask for it
– Scoped: An instance of the service type is created once per
request and will be shared in a session
108
Injecting dependency in Controller
public class EmployeesController : Controller
{
IEmployeeRepository _repository = null;
Public EmployeesController(IEmployeeRepository repository)
{
_repository = repository;
}
public IActionResult Index()
{
return View(_repository.GetEmployees());
}
}
109
LAB: Repository
• Create ASP.NET Core MVC project
• Employee Model
• Validations
• Employee controller
• Add Folder Repositories
• Generic Repository interface
• Employee Repository class
• Register repository as dependent service (in Startup
ConfigureServices)
• Implement other actions: Create, Edit, Delete, Details
110
LAB – EMS with Repository pattern
• Employee Controller
• List
• Create
• Edit
• Delete
• Details
• Search by employee id, gender, job title
111
Entity Framework Core
112
Introduction in Entity Framework
113
Introduction in Entity Framework
Tip: Use EF6 for Windows platform applications until EF Core becomes more stable
and implements more features. Use EF Core for cross-platform development.
https://docs.microsoft.com/en-us/ef/efcore-and-ef6
114
Entity Framework Core (EF Core)
Lightweight &
ORM LINQ support
Cross-
platform
115
EF Core
Entity Framework
Code Databas
e
116
EF Core : Approaches
117
Server Side (IIS, Kestrel)
Request
Middleware
EF (Database First)
Routing Database
{controller}/
{action}/{id?}
SQL Server
Controller Calls
Action method
Tables/View/
Stored
DbContext
Procedure
Response (HTML) Returns data
View
118
LAB: Table Schema
• Create database tables
Create tables & data.sql
119
Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-
Schemas>] [-Tables>] [-DataAnnotations] [-Force] [-Project] [-StartupProject]
[<CommonParameters>]
Database First
EF Core – Nuget packages
• PM> Install-Package
• Microsoft.EntityFrameworkCore.SqlServer
• Microsoft.EntityFrameworkCore.Tools
121
LAB: EMS with EF Core
• Create Project
• Install packages
• Microsoft.EntityFrameworkCore.SqlServer
• Microsoft.EntityFrameworkCore.Tools
122
PM> Scaffold-DbContext
"Server=.;Database=EmsDB;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
124
Server Side (IIS, Kestrel)
Request
Middleware
EF (Database First)
Routing Database
{controller}/
{action}/{id?}
SQL Server
Controller Calls
Action method
Tables/View/
Stored
DbContext
Procedure
Response (HTML) Returns data
View
125
LAB: EMS with EF Core (Database
First)
• Create Project
• Install packages
• Microsoft.EntityFrameworkCore.SqlServer
• Microsoft.EntityFrameworkCore.Tools
• PM Console
• Scaffold-DbContext
"Server=.;Database=EmsDB;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
• Add Employees Controller
• Run and check error ??
126
LAB: EMS with EF Core (Database
First)
• Create Project
• Install packages
• Microsoft.EntityFrameworkCore.SqlServer
• Microsoft.EntityFrameworkCore.Tools
• PM Console
• Scaffold-DbContext
"Server=.;Database=EmsDB;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
• Add Employees Controller
• Add EmsDbContext as dependency service
127
Revision
• Repository pattern • EMS
• Entity Framework • Employees Controller
• No Manager
• Database First
• Edit
• Nuget Packages
• Delete
• Scaffold-DbContext
• Details
• DbContext
• Get Employees by Department
• DBSet
• Connection string
• Departments Controller
• Register DbContext as • Entity Framework
dependency
• Code First
• Controller (Scaffolding)
• View changes
128
Server Side (IIS, Kestrel)
Request
Middleware
EF (Database First)
Routing Database
{controller}/
{action}/{id?}
SQL Server
Controller Calls
Action method
Tables/View/
Stored
DbContext
Procedure
Response (HTML) Returns data
View
129
LAB: EMS with EF Core (Database
First)
• Create Project
• Install packages
• Microsoft.EntityFrameworkCore.SqlServer
• Microsoft.EntityFrameworkCore.Tools
• PM Console
• Scaffold-DbContext "Server=.;Database=EmsDB;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
• Add Employees Controller
• Add EmsDbContext as dependency service
• Employees Controller Employees By Department
130
Lab: EF Database First
• EMS
• Employees Controller
• No Manager
• Edit
• Delete
• Details
• Get Employees by Department
• Departments Controller
131
DB First Approach
use the Migration commands whenever you change the model to keep the database up
to date with the model
132
EF Core
• Code First
• Create Model classes first
• Migration
• Database Schema
133
LAB: EF, Code First
• Movie application • Add validations
• Movie model • Movies Controller
• Id
• Name • List
• Release date • Create (only authenticated user)
• Genre • Edit (only authenticated user)
• Rating • Delete (only authenticated user)
• Actors
• Details
• Actor
• Id • Business rules
• Name • Genre
• Gender • Rating (1 to 10)
• Movie
134
EF Core – Primary Key
• Use conventions!
<ClassName>Id or just Id
• Annotations
[Key]
• Fluent API
modelBuilder.Entity<ModelClass>().HasKey(c => c.KeyProperty);
• Composite key – only in Fluent API
modelBuilder.Entity<ModelClass>().HasKey(
c => new { c.KeyProperty1, c.KeyProperty2 });
135
Server Side (IIS, Kestrel)
Repository
Request
Middleware Interface
Class
Routing Database
{controller}/
{action}/{id?} Method
SQL Server
Controller Calls
Action method
Calls DbContext Tables/View/
Stored
Model
Procedure
Response (HTML) Returns data
Returns
View data EF (Database First/
Code First)
136
EF Core: Code First
137
LAB: EF, Code First
• Movie application • Add validations
• Movie model • Movies Controller
• Id
• Name • List
• Release date • Create (only authenticated user)
• Genre • Edit (only authenticated user)
• Rating • Delete (only authenticated user)
• Actors
• Details
• Actor
• Id • Business rules
• Name • Genre
• Gender • Rating (1 to 10)
• Movie
138
The Database Context
public class MovieContext : DbContext
{
public AppDbContext
(DbContextOptions<MovieContext> options): base(options)
{
}
public DbSet<Employee> Employees
{
get; set;
}
} 139
Connection String in AppSettings.json
{
"ConnectionStrings": { "DefaultConnection":
"Server=.;
Database=MoviesDB;
Trusted_Connection=True;
MultipleActiveResultSets=true“
}
}
140
Startup Changes
141
Server Side (IIS, Kestrel)
Repository
Request
Middleware Interface
Class
Routing Database
{controller}/
{action}/{id?} Method
SQL Server
Controller Calls
Action method
Calls DbContext Tables/View/
Stored
Model
Procedure
Response (HTML) Returns Returns data
View data EF (Database First/
Code First)
142
LAB: Movie application
• ASP.NET MVC, Identity • Movie model
• Movie model • Add validations
• DbContext • Business rules
• Genre
• ConnectionString • Rating (1 to 10)
• Repository • Movies Controller
• List
• Create (only authenticated user)
• Edit (only authenticated user)
• Delete (only authenticated user)
• Details
143
LAB: Movie application
• ASP.NET MVC, Identity • Movie model
• Movie model • Add validations
• DbContext • Business rules
• Genre
• ConnectionString • Rating (1 to 10)
• Repository • Movies Controller
• Inject MovieContext in • List
Repository • Create (only authenticated user)
• Edit (only authenticated user)
• Register MovieRepository as
• Delete (only authenticated user)
dependent service • Details
144
LAB: Movie application
• ASP.NET MVC, Identity • Movie model
• Movie model • Add validations
• DbContext • Business rules
• Genre
• ConnectionString
• Rating (1 to 10)
• Repository • Movies Controller
• Inject MovieContext in Repository • List
• Register MovieRepository as • Create (only authenticated user)
dependent service • Edit (only authenticated user)
• Delete (only authenticated user)
• Migration • Details
145
Creating the Database
Create
database
Database migration
Databas
Package Manager Console e
Commands
>add-migration
<MigrationName> 146
What EF Core Does for You
Clas Tabl
s e
p u b l i c class Employee
{ EmployeeId Int (PK)
p u b l i c i n t EmployeeId { g e t ; s e t ; } Name String
147
LAB: Movie application
• ASP.NET MVC, Identity • Movie model
• Movie model • Add validations
• DbContext
• Business rules
• ConnectionString • Genre
• Repository • Rating (1 to 10)
• Inject MovieContext in Repository • Movies Controller
• Register MovieRepository as dependent • List
service • Create (only authenticated user)
• Migration • Edit (only authenticated user)
• Movies Controller • Delete (only authenticated user)
• Inject MovieRepository in Controller • Details
148
Server Side (IIS, Kestrel)
Repository
Request
Middleware Interface
Class
Routing Database
{controller}/
{action}/{id?} Method
SQL Server
Controller Calls
Action method
Calls DbContext Tables/View/
Stored
Model
Procedure
Response (HTML) Returns Returns data
View data EF (Database First/
Code First)
149
Revision
• Entity Framework Core • EF Core Code First
• Database First • Security (Identity)
• Employees
• Departments • Web API
• Code First • Migration/Porting
• One to Many Relationship
• Movie App
• Postman
https://www.postman.com/dow
nloads
150
LAB: Movie application
• ASP.NET MVC, Identity • Movie model
• Movie model • Add validations
• DbContext • Business rules
• ConnectionString • Genre
• Rating (1 to 10)
• Repository
• Inject MovieContext in Repository • Actors Controller
• Register MovieRepository as dependent • Movies Controller
service • List
• Create (only authenticated user)
• Migration
• Edit (only authenticated user)
• Movies Controller • Delete (only authenticated user)
• Inject MovieRepository in Controller • Details
151
EF Core – Indexes
• Index is created for every foreign key
• Annotations – not possible
• Fluent API
• Single property, non-unique
modelBuilder.Entity<ModelClass>() .HasIndex(b => b.SomeProperty);
• Unique
modelBuilder.Entity<ModelClass>() .HasIndex(
b => b. SomeProperty) .IsUnique();
• More than one property
modelBuilder.Entity<ModelClass>() .HasIndex(
p => new { p. SomeProperty1, p. SomeProperty2 });
152
EF Core – Table/Column mapping
• Annotations
[Table(“TableName”)]
[Column(“ColumnName”)]
• Fluent API
modelBuilder.Entity<ModelClass>() .ToTable(”TableName");
modelBuilder.Entity<ModelClass>() .Property(
b =>
b.SomeProperty) .HasColumnName(”ColumnName");
153
EF Core – Default value
• Fluent API
modelBuilder.Entity<ModelClass>().Property(
b => b.SomeNumber) .HasDefaultValue(3);
modelBuilder.Entity<ModelClass>().Property(
b => b.SqlProperty) .HasDefaultValueSql("getdate()");
154
_appDbContext.Employees.
Include(c => c.Category).Where(p => p.IsEmployeeOfTheWeek);
_appDbContext.Orders.Add(order);
_appDbContext.SaveChanges();
156
Creating and Initializing the
Database
157
Creating the Database
Create
database
Database migration
Databas
Package Manager Console e
Commands
>add-migration
<MigrationName> 158
Initializing the Database
Initial data
159
Modifying the
Model
160
Modifying the Model
Update
database
migration Commands
>add-migration
<MigrationName> 161
Entity Framework Core - Relationships
162
More about EF Core
• https://www.entityframeworktutorial.net/efcore/entity-framework-co
re.aspx
• https://www.learnentityframeworkcore.com
163
Web API
RESTful APIs
164
Server Side (IIS, Kestrel)
Repository
Request
Middleware Interface
Class
Database
1) Routing
{controller}/{id?} Method
2) HTTP method? SQL Server
Controller Calls
Web application/
Action method Calls
Desktop App / DbContext Tables/View/
Mobile App Stored
Model
Procedure
Response Returns Returns data
StatusCode
(Data) data EF (Database First/
Code First)
165
Server Side (IIS, Kestrel)
Request
Middleware
1) Routing
{controller}/{id?}
2) HTTP method?
Controller
Web application/
Action method
Desktop App /
Mobile App
Model
Response StatusCode
(Data)
166
"RESTful Web Services" model
170
Web API connects to all HTTP aware clients
172
Web API Controllers
• A controller class handles HTTP requests
• Web API controllers derive from ApiController
• ASP.NET Web API by default maps HTTP requests to specific methods called "actions"
Action HTTP method Relative URI Method
Get a list of all
products
GET /api/products Get()
Get a product by ID GET /api/products/id Get(int id)
Create a new product POST /api/products Post(ProductModel value)
http://localhost:1337/api/posts
http://localhost:1337/api/posts
routes.MapHtpRoute(name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RoutesParameter.Optional });
175
LAB: Web API project (ASP.NET Core)
• Products.InMemory.API • ProductsController
• Product • Test
• Id • Get All products
• Name • Get product by id
• DateAdded
• Price (> 0)
• Category
176
LAB: Web API project (ASP.NET Core)
• Products.InMemory.API • ProductsController
• Product • Test
• Id • Get All products
• Name • Get product by id
• DateAdded • Add a product (POST)
• Price (> 0)
• Category
177
ApiController: Action Result 1
Method Decription
Created(String, Object) Creates a CreatedResult (201 Created) with the specified values.
Created(Uri, Object) Creates a CreatedResult (201 Created) with the specified values.
InternalServerError(Exception) Creates an ExceptionResult (500 Internal Server Error) with the specified
exception.
Json<T>(T, JsonSerializerSettings) Creates an JsonResult (200 OK) with the specified values.
181
ApiController: Action Result 3
Method Decription
182
API Action return guidelines
• Always return the appropriate status code, however you define
"appropriate".
• Use the shortcut methods (e.g. Ok(), NotFound(), etc.) when
possible.
• An action that returns void will send status code 204 No Content.
• An action which returns an object will send 200 OK.
• Use HttpResponseMessage for status codes that are not supported
by shortcut methods.
• Use HttpResponseException for error status codes.
183
https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.1
-
-
-
-
-
LAB: Web API project (ASP.NET Core)
• Products.InMemory.API • ProductsController
• Product • Test
• Id • Get All products
• Name • Get product by id
• DateAdded • Add product (POST)
• Price • Update product (PUT)
• Category • Delete Product
• Get products by Category
188
Consuming API
• ASP.NET Core MVC
• Nuget package
• Microsoft.AspNet.WebApi.Client
189
Server Side (IIS, Kestrel)
API
Request
Middleware
Routing Database
{controller}/
{action}/{id?} HTTP Method
SQL Server
Controller Calls
Action method
Calls DbContext Tables/View/
Stored
Model HTTPClient Procedure
Response (HTML) Returns Returns data
View data EF (Database First/
Code First)
190
LAB: Web API project (ASP.NET Core)
• Products MVC App • API
• Product Model • ProductsController
• Get All products
• ProductsController • Get product by id
• List • Add product (POST)
• Create • Update product (PUT)
• Edit • Delete Product
• Get products by Category
• Delete
• Details
• ProductsByCategory
191
Consuming API: Get List
IEnumerable<Employee> employeesList = null;
client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response =
client.GetAsync("employees").Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content
.ReadAsAsync<IEnumerable<Employee>>().Result;
employeesList = result;
return employeesList;
}
else
{
throw new Exception(response.ReasonPhrase); 192
Consuming API: Add/Create
client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response =
client.PostAsJsonAsync("employees", employee).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content
.ReadAsAsync<Employee>().Result;
if (result == null)
{
return false;
}
else
{
return true;
}
}
else
{
throw new Exception(response.ReasonPhrase);
}
193
Migration from .NET framework
• .NET Portability Analyzer
• Analyzes assemblies and provides a detailed report on .NET APIs that are
missing for the applications or libraries to be portable
• Visual Studio Extension
• .NET API analyzer
• analyzes whether you're using an API in a way that will throw a
PlatformNotSupportedException at run time
• dotnet try-convert
• https://github.com/dotnet/try-convert
194
Migration from .NET framework
• If you're using Windows-specific APIs (such as registry access), install
the Windows Compatibility Pack
• EF to EF Core
• https://docs.microsoft.com/en-us/ef/efcore-and-ef6
• References Nuget packages
195
Content
• .NET Core • Repository pattern
• .NET Core CLI • Entity framework Core
• ASP.NET MVC Core • Web API
• Model, View, Controller
• Migration
• Action Methods
• Routing
• Middleware
• Tag helpers
• Dependency injection
• Security
196
Post test
https://www.surveymonkey.com/r/PGDLKZF
197
Daily Session Feedback
https://www.surveygizmo.com/s3/5592770/Pulse-Check-Survey-Techni
cal-Training-Programs