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

1 ASP - Net Core MVC, Web API, Ef, Repo

.net

Uploaded by

Rajesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

1 ASP - Net Core MVC, Web API, Ef, Repo

.net

Uploaded by

Rajesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 195

.

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

• Check lab access


• Verify Visual Studio, SSMS, Postman are installed
• Open Visual Studio

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.

Assembly Dll Exe and dll

Shared Shared location as per platform GAC


assemblies

Packages/ PackageReference (nuget packages) packages.config or References


References
10
CLI

11
.NET Core CLI
• Command Line Interface
• Commands
https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet?tabs=netcore21#
dotnet-commands

• Version of .NET Core


• dotnet --version
• dotnet help
• First time access will download nuget packages in shared location (~ GAC)
• dotnet help new
• dotnet new --help
• .NET Core Console App – Hello World 12
.NET Command Line Interface (CLI) Command

Basic Commands Description

Creates a new project, configuration file, or solution based on


new
the specified template.

restore Restores the dependencies and tools of a project.

build Builds a project and all of its dependencies.

Runs source code without any explicit compile or launch


Run
commands.

Packs the application and its dependencies into a folder for


publish
deployment to a hosting system.

test Executes unit tests.

13
.NET Core CLI
• Create new project with dotnet new
• Edit packages in project.json

• Restore them with dotnet restore

• Write some C#

• Start the application with dotnet run

14
LAB
• “Hello CGI” console application

dotnet new console –name HelloCGI


dotnet restore
dotnet build
dotnet run

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

2008 2017 2019


ASP.NET MVC ASP.NET Core 2.0 ASP.NET Core 3.0

23
LAB - Employee Management
System
• Create ASP.NET Web app – Ems_Mvc_InMemory
• Use ASP.NET MVC template

• Project folder structure


• Metapackage
• Kestrel server
• Middleware
• Register dependency services
• Configuration
24
Metapackage and runtime store
• Metapackage
• adds references to list of packages
• Microsoft.AspNetCore.All: adds all ASP.NET Core packages
• Runtime store
• Location on disk containing packages
• Faster deployment
• Lower disk space use
• Improved startup performance

25
Site Configuration

26
Project Structure

27
Program.c
s
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>


Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

28
Program.c
s

public class Program


{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}

29
Startup.cs

public class Startup


{
public void ConfigureServices(IServiceCollection services)
{
...
}

public void Configure(IApplicationBuilder app,


IHostingEnvironment env)
{
...
}

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)


{
//add middleware components here
}

33
Middleware Request
Pipeline

Request

Middl Middl Middl


e e e
ware ware ware
1 2 3
Respons
e

34
Configure
Method

public void Configure(IApplicationBuilder app, IHostingEnvironment env)


{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseEndpoints(endpoints =>
{ ... });
}

35
Ordering Middleware
Components

Request

Middl Middl Middl


e e e
ware ware ware
1 2 3
Respons
e
Response Static End Point
Compressio
n Files
36
The Startup of the
Application

Application ConfigureServices method


Ready for requests
starting Registering services
Program class

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.

Renders a partial view, that defines a section of a view


PartialViewResult PartialView that can be rendered inside another view.

RedirectResult Redirect Redirects to another action method by using its URL.

RedirectToAction
RedirectToRouteResult RedirectToRoute Redirects to another action method.

ContentResult Content Returns a user-defined content type.


JsonResult Json Returns a serialized JSON object.

JavaScriptResult JavaScript Returns a script that can be executed on the client.

FileResult File Returns binary output to write to the response.

Represents a return value that is used if the action


EmptyResult (None) method must return a null result (void).
46
ActionResult and Controller methods
Result Class Description Base Controller Method

ViewResult Represents HTML and markup. View()

EmptyResult Represents No response.


ContentResult Represents string literal. Content()
FileContentResult,
FilePathResult, Represents the content of a file File()
FileStreamResult

JavaScriptResult Represent a JavaScript script. JavaScript()

JsonResult Represent JSON that can be used in AJAX Json()

RedirectResult Represents a redirection to a new URL Redirect()

RedirectToRouteResult Represent another action of same or other RedirectToRoute()


controller
PartialViewResult Returns HTML PartialView()
HttpUnauthorizedResult Returns HTTP 403 status 47
Action Method Parameters
• Can be primitive data type or complex type
• Can be Nullable Type
[HttpPost]
public ActionResult Edit(Employee employee)
{
// update student to the database
return RedirectToAction("Index");
}

[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

public class Order


{
[Required(ErrorMessage = "Enter your first name")]
[StringLength(50)]
public string FirstName { get; set; }
}

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>

• Generates the following HTML:


<label for=“FirstName”>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”

Single, Double 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

<label asp-for=“FirstName" class="col-md-2 control-


label"> </label>

<label class="col-md-2 control-label"


for="FirstName">FirstName</label>

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:

• IntelliSense helps very much here

@Html.Label("FirstName", "First Name:", new { @class = "captio


n" })

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

Response (HTML) Returns


View data

97
public interface IEmployeeRepository
{
IEnumerable<Employee> GetAllEmployees();
Employee GetEmployeeById(int employeeId);
}

Employee Repository Interface

98
LAB: Repository
• Create ASP.NET Core MVC project
• Employee Model
• Employee controller
• Add Folder Repositories
• Generic Repository interface

99
Repository Implementation

public class EmployeeRepository : IEmployeeRepository


{
public IEnumerable<Employee> GetEmployees()
{
return ...
}

public Employee GetEmployeeById(int employeeId)


{ ... }
}
100
LAB: Repository
• Create ASP.NET Core MVC project
• Employee Model
• Employee controller
• Add Folder Repositories
• Generic Repository interface
• Employee Repository class

101
Registering the Repository

Services
Repository “Consumer” class
Startup
class

102
public void ConfigureServices(IServiceCollection services)
{
//register framework services
services.AddMvc();

//register our own services


services.AddScoped<IRepository, MockEmployeeRepository>();
}

Registering Services in ConfigureServices

103
Registration options

AddTransient AddSingleton AddScoped

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

Response (HTML) Returns


View data

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

• What is Entity Framework?


• Pros/Cons in using EF Core

It is an ORM => object relational


mapping tool from Microsoft

113
Introduction in Entity Framework

• What is Entity Framework?


• Pros/Cons in using EF Core
Pros Cons
Is available for .NET Core => can be used Does not support the old EDMX design
for Mac, Linux or Windows time
Supports modern cloud-based, non- Does not support yet complex
relational databases (Azure Table Storage, inheritance models
Redis)

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

SQL Server and


Open-source other, non-relational Code-first
DB support

115
EF Core

Entity Framework

Code Databas
e

116
EF Core : Approaches

Database First Code First

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

• Create EmsDB database, create tables


• Visual Studio, Tools -> NuGet Package Manger ->
Package Manger Console
• run the command
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

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

Domain classes Database context

Application configuration Packages (.NET Core 3)

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

public void ConfigureServices(IServiceCollection services)


{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString
("DefaultConnection")));
}

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

p u b l i c s t r i n g Name { g e t ; s e t ; } Description string


p u b l i c s t r i n g Description { g e t ; s e t ; }
}

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

Querying for Data


Modifying Data
foreach (var shoppingCartItem in shoppingCartItems)
{
var orderDetail = new OrderDetail
{
Amount = shoppingCartItem.Amount,
EmployeeId =
shoppingCartItem.Pie.PieId, Price =
shoppingCartItem.Pie.Price
};
order.OrderDetails.Add(orderDetail);
}

_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

HasData() on the Databas


DbContext (migration) e

159
Modifying the
Model

160
Modifying the Model

Update
database

Model change Databas


Database e

migration Commands
>add-migration
<MigrationName> 161
Entity Framework Core - Relationships

• One to One => 1:1


• One to Many => 1: many
• Many to Many =>
many : many

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

Web API Web API Web API

Browsers Devices Phones Tablets


CRUD Operations in REST APIs

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)

Update a product PUT /api/products/id Put(int id, ProductModel value)

Delete a product DELETE /api/products/id Delete(int id)


Get products by
category
GET /api/products?category=grocery Get(string category)
173
Web API
1 Default
2 Behavior
3
API Controller
Web Request Match a Route
Responds

http://localhost:1337/api/posts

HTTP GET Controller


Request Name

public class PostsController : ApiController


{
public string Get()
{
return "Some data";
}
}
174
Default Route
• Web API also provides smart conventions by default
• We can create classes that implement Web APIs without having to explicitly write
code
• HTTP Verb is mapped to an action name

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

BadRequest() Creates a BadRequestResult (400 Bad Request).

BadRequest(ModelStateDictionary) Creates an InvalidModelStateResult (400 Bad Request) with the specified


model state.

Creates a BadRequestErrorMessageResult (400 Bad Request) with the


BadRequest(String) specified error message.

Created(String, Object) Creates a CreatedResult (201 Created) with the specified values.

Created(Uri, Object) Creates a CreatedResult (201 Created) with the specified values.

Creates a CreatedAtRouteResult (201 Created) with the specified values.


CreatedAtRoute(String, Object, Object) CreatedAtRoute(routeName, routeValues, content);
180
ApiController: Action Result 2
Method Decription

InternalServerError() Creates an InternalServerErrorResult (500 Internal Server Error).

InternalServerError(Exception) Creates an ExceptionResult (500 Internal Server Error) with the specified
exception.

Json<T>(T, JsonSerializerSettings, Encodin


g) Creates an JsonResult (200 OK) with the specified values.

Json<T>(T, JsonSerializerSettings) Creates an JsonResult (200 OK) with the specified values.

Json<T>(T) Creates an JsonResult (200 OK) with the specified value.

NotFound() Creates an NotFoundResult (404 Not Found).

Ok() Creates an OkResult (200 OK).

Ok<T>(T) Creates an OkObjectResult (200 OK) with the specified values.

181
ApiController: Action Result 3
Method Decription

Redirect(Uri) Creates a RedirectResult (302 Found) with the specified value.

Redirect(String) Creates a RedirectResult (302 Found) with the specified value.

Creates a RedirectToRouteResult (302 Found) with the specified


RedirectToRoute(String, Object) values.
RedirectToRoute(routeName, routeValues)
Creates a StatusCodeResult with the specified status code.
StatusCode(HttpStatusCode) HttpStatusCode => Enum

ResponseMessage(HttpResponseMessage) Creates a ResponseMessageResult with the specified response.

Content(Object) returns plain text formatted data

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

You might also like