Web Programming - ASP - Net Core (001-131)
Web Programming - ASP - Net Core (001-131)
ASP.NET Core
Hans-Petter Halvorsen
https://www.halvorsen.blog
Web Programming
ASP.NET Core
Hans-Petter Halvorsen
2021
Preface
This textbook gives an overview of Web and Web programming in general and with focus on
ASP.NET and ASP.NET Core. ASP.NET and ASP.NET Core are web development frameworks
created by Microsoft.
The only way to learn programming is to do a lot of coding by yourself, and not only small
code snippets with a few lines of code. You need to make large Applications. It takes time
and may be demanding, but that’s the only way! The reward is knowledge that goes deep,
and you will gain skills that is highly desired by the industry.
Web Page:
ASP.NET: https://www.halvorsen.blog/documents/programming/web/aspnet/
Videos:
https://www.youtube.com/watch?v=lcQsWYgQXK4&list=PLdb-
TcK6Aqj34rTHSk6C1jZQgeALWS1qO
Here you will find videos that introduces the ASP.NET Core topics covered in this textbook.
Hans-Petter Halvorsen
The author currently works at the University of South-Eastern Norway. The author has been
working with Software Engineering and Industrial IT Projects for more than 20 years.
My Web Site:
https://www.halvorsen.blog/
https://www.youtube.com/IndustrialITandAutomation
https://www.halvorsen.blog
Table of Contents
Preface ............................................................................................................................. 2
Part 1 : Introduction ....................................................................................................... 12
1 Introduction............................................................................................................. 13
1.1 Applications...................................................................................................... 14
1.2 .NET.................................................................................................................. 15
1.3 Web ................................................................................................................. 16
2 ASP.NET................................................................................................................... 17
2.1 ASP.NET Web Forms ......................................................................................... 18
2.2 ASP.NET Core with Razor .................................................................................. 18
Part 2 : Visual Studio and C# ........................................................................................... 20
3 Visual Studio............................................................................................................ 21
3.1 Visual Studio macOS ......................................................................................... 22
4 Desktop Applications ............................................................................................... 25
4.1 Windows Forms App ......................................................................................... 25
4.2 WPF Application ............................................................................................... 25
4.3 Universal Applications ...................................................................................... 25
5 C# Programming Language ...................................................................................... 26
5.1 Introduction ..................................................................................................... 26
5.2 Classes .............................................................................................................. 27
5.3 Inheritance ....................................................................................................... 27
6.8.1 PHP.................................................................................................................................................. 42
6.8.2 ASP.NET........................................................................................................................................... 43
7 HTML....................................................................................................................... 46
7.1 HTML in Visual Studio ....................................................................................... 47
7.2 HTML Tags ........................................................................................................ 47
5
7.2.7 Comments ....................................................................................................................................... 49
6
12.6 Razor Pages ...................................................................................................... 79
12.6.1 Sending data from the Page Model to the Razor File ................................................................. 80
7
17.1.6 New Book ................................................................................................................................. 139
8
22.2 Final System ................................................................................................... 186
23 Web API ............................................................................................................. 188
Part 9 User Login and ASP.NET Core Identity ................................................................. 189
24 User Identity and Login ...................................................................................... 190
24.1 Password Security ........................................................................................... 190
25.2.1 Create Project in Visual Studio with Identity Enabled .............................................................. 200
9
Part 11 Deployment...................................................................................................... 218
27 Web Servers ....................................................................................................... 219
28 Deployment in Visual Studio ............................................................................... 222
29 Internet Information Services (IIS) ...................................................................... 223
29.1 Installation ..................................................................................................... 223
10
35.4.1 appSettings.json ....................................................................................................................... 242
11
Part 1 : Introduction
This part introduces the topics covered in this textbook and puts it into a proper context.
That’s why you need to know basic Web Programming, including HTML, CSS and JavaScript.
To create more powerful Web Sites and Web Applications you also need to know about
Web Servers, Database Systems and Web Frameworks like PHP, ASP.NET, etc.
It all started with Internet (1960s) and the World Wide Web - WWW (1991). The first Web
Browser, Netscape, came in 1994. This was the beginning of a new era, where everything is
connected on internet, the so-called Internet of Things (IoT).
• Part 1: Introduction
• Part 2: Visual Studio and C#
• Part 3: Web Fundamentals
• Part 4: ASP.NET Core
1.1 Applications
We can separate applications in different categories:
• Desktop Applications
• Web Applications
• Mobile Applications
These will shortly be described below. In this textbook we will focus on creating web
applications using ASP.NET Core.
Windows Forms Apps are the oldest but are still very popular.
We have:
14
1. Introduction
We have:
• iOS
• Android
• iPadOS
• etc.
The great thing about Web Applications is that they also work on Mobile platforms. Native
apps for Android phones and Apple devices typically need to be developed in a strict
environment and with specific programming languages and they only work for the platform
they are developed for. For Android development you typically will use the Kotlin
programming language in combination with Android Studio. While for development for the
Apple platform you will need a Mac computer and use the Swift programming language as
part of the Xcode development environment.
1.2 .NET
The .NET is a development platform from Microsoft.
.NET Framework was first introduces in 2002 and works only for the Windows operating
system, while .NET Core was introduced in 2016. .NET Core is cross-platform, meaning it will
work on Windows, Linux and macOS.
The newly released .NET 5 has merged .NET Framework and .NET Core into a more unified
package.
.NET Core and the newly released .NET 5 (that is built on .NET Core) will be the future of
.NET. Microsoft is still committed to support the previous .NET Framework for years to
come, but for new applications your choice should be .NET 5 either you want to develop
desktop applications (“Windows Forms App”) or web applications (“ASP.NET Core Web
App”).
15
1. Introduction
You can use many different programming languages with .NET, but the “default” language is
C#, which is the language we will use in this textbook.
1.3 Web
We have 2 types of web pages:
Static web pages are pure HTML web pages where the contents is written in manually and it
doesn’t change unless the user updates the contents.
Dynamic Web Pages typically get contents from a Database and have deeper interaction
with the user.
Dynamic Web Pages using e.g., ASP.NET or PHP Executes Code on the Server-side and
Generates HTML Code that is sent to the Client (Web Browser). This is known as Server-side
code.
You can also create Dynamic content on the Client using JavaScript.
Static Web Pages typically contains Text and Images that is not changing (unless a person
changes the page and upload a new version). Static Web Pages are Pure HTML pages
Video:
16
2 ASP.NET
ASP.NET is an open-source web framework, created by Microsoft, for building web apps and
services using the .NET Framework or the .NET Core. We have both ASP.NET and ASP.NET
Core. ASP.NET Core is the new approach built on .NET Core.
• ASP.NET Web Forms - The same programming model as WinForms. If you already
know WinForms, this is an easy access to the world of web programming.
• ASP.NET MVC (Model-View Controller). If you are familiar with the MVC approach,
this could be your choice.
• ASP.NET with Razor Pages - This is the latest and recommended way. This has
become the "default" approach for ASP.NET today. It mixes the best from all the
others combined with PHP like syntax (PHP is probably the most popular Web
Framework today)
Still, if you want to get an overview of ASP.NET Web Forms you may take a look at the
following:
This textbook will focus on Razor with Page Model (Code and Layout are separated in
different Files).
An ASP.NET Razor page has the “.cshtml” (e.g., “Index.cshtml”) file extension. This file
contains a mix of HTML and Razor syntax. The Razor syntax is actually C# code mixed
together with the HTML code.
The Razor parts of the file are executed on the web server before the page is sent to the
client (your web browser).
18
14. Database Systems
The Razor page may also have a C# code file linked to it, this file has the extension
“.cshtml.cs” (e.g., “Index.cshtml.cs”). The “.cshtml.cs” file is called the Page Model.
• A “.cshtml” file that contains HTML markup with C# code using Razor syntax.
• A “.cshtml.cs” (“code behind”) file that contains C# code that handles page events.
In this textbook we will go through ASP.NET Core in detail. In Part 3: Web Fundamentals we
go through the foundations for creating web applications in general, while in Part 4:
ASP.NET Core we start creating ASP.NET Core Web Applications. If you cannot wait to start
with ASP.NET Core, you take sneak peek at the introduction videos below.
Videos:
19
Part 2 : Visual Studio
and C#
This part gives an overview of Visual Studio and basic C# programming, which will be the
foundation for learning and development of ASP.NET Core Web Applications. If you already
are familiar with using Visual Studio and C# for development of Windows Forms Apps, you
can skip this part.
New projects are created from the “New Project” window (Figure 3-2).
Figure 3-3 shows the New Project window in Visual Studio for macOS.
22
3. Visual Studio
If you want to make Web Applications and you have a Mac, the Visual Studio for macOS has
become an excellent choice.
.NET Framework:
.NET Core:
• ASP.NET Core Web Application (Razor) – This is the default and recommended
option.
• ASP.NET Core Web Application (MVC)
• Angular Web Applications
• React.js Web Applications
• Web API
• etc.
23
3. Visual Studio
This means you have all the necessary tools available to create great web applications using
C# on your Mac.
24
4 Desktop Applications
In the latest version of Visual Studio 2019 we can develop WinForms Desktop Applications
and WPF Desktop Applications for both .NET Framework (4.x) and .NET Core (3.x).
.NET WinForms vs. .NET Core WinForms: Note that .NET Core is cross-platform, but .NET
Core WinForms Desktop Application will (of course) only work on Windows.
The first step in OOP is to identify all the objects you want to manipulate and how they
relate to each other, an exercise often known as data modeling. Once you've identified an
object, you generalize it as a class of objects and define the kind of data it contains and any
logic sequences that can manipulate it. Each distinct logic sequence is known as a method. A
real instance of a class is called an “object” or an “instance of a class”. The object or class
instance is what you run in the computer. Its methods provide computer instructions and
the class object characteristics provide relevant data. You communicate with objects - and
they communicate with each other.
Simula was the first object-oriented programming language. Simula was developed in the
1960s by Kristen Nygaard from Norway.
Java, Python, C++, Visual Basic .NET and C# are popular OOP languages today.
C# Documentation: https://docs.microsoft.com/en-us/dotnet/csharp/
5.2 Classes
Classes are the fundamental building blocks in C#.
5.3 Inheritance
Inheritance is a feature of object-oriented programming languages that allows you to define
a base class that provides specific functionality (data and behavior) and to define derived
classes that either inherit or override that functionality.
5.3.1 Example
Assume you have different types of sensors sharing some common features, then you can,
e.g., have a Base Class called Sensor() and then other derived Classes like
TemperatureSensor(), etc. that either inherit or override the functionality of the base class.
If you have different types of Temperature Sensor, you can make derived classes like
Thermistor() that inherit/ override functionality of TemperatureSensor(). See Figure 5-1.
27
5. C# Programming Language
28
5. C# Programming Language
5.4 Polymorphism
Polymorphism is an object-oriented feature that is part of all object-oriented programming
languages.
5.4.1 Example
5.5 Interfaces
Interfaces are used along with classes to define what is known as a contract. A contract is an
agreement on what the class will provide to an application.
An interface declares the properties and methods. It is up to the class to define exactly what
the method will do.
An interface is a completely "abstract class", which can only contain abstract methods and
properties (with empty bodies).
It is considered good practice to start with the letter "I" at the beginning of an interface, as
it makes it easier for yourself and others to remember that it is an interface and not a class.
Note: Interfaces can contain properties and methods, but not fields
29
5. C# Programming Language
5.5.1 Example
Assume you make this system as an open platform meaning other developers can use it to
add logging functionality from other sensors.
The system will not work if they don’t implement a Name for the Sensor and a ReadValue()
method.
To make sure that they follow this, you should implement Interfaces
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class. To implement an interface, use the : symbol (just like with inheritance).
The body of the interface method is provided by the "implement" class. Note that you do
not have to use the override keyword when implementing an interface.
5.6 Generics
Generics allow you to define the specification of the data type of programming elements in
a class or a method, until it is actually used in the program. In other words, generics allow
you to write a class or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data
types. When the compiler encounters a constructor for the class or a function call for the
method, it generates code to handle the specific data type.
30
5. C# Programming Language
W3Schools: https://www.w3schools.com/cs/index.php
Videos:
Below you find some videos regarding Visual Studio and C# programming creating Windows
Forms Apps:
31
Part 3 : Web
Fundamentals
This part gives an overview of the fundamentals in web and web programming. ASP.NET
Core is a framework for creating Web Applications, this means you need to have basic
knowledge about the web and web programming in general before you can start creating
ASP.NET Core Web Applications.
If you already are familiar with the fundamentals of the web, familiar with creating HTML
web pages and have used, e.g., PHP for creating Web Applications, you can skip this part.
It all started with Internet (1960s) and the World Wide Web - WWW (1991). The first Web
Browser, Netscape, came in 1994. This was the beginning of a new era, where everything is
connected on internet, the so-called Internet of Things (IoT).
That’s why you need to know basic Web Programming, including HTML, CSS and JavaScript.
To create more powerful Web Sites and Web Applications you also need to know about
Web Servers, Database Systems and Web Frameworks like PHP, ASP.NET, etc.
Use HTML to define the content of web pages, CSS is used to specify the layout of web
pages, while JavaScript is used to program the behavior of web pages.
For creating more dynamic web pages, we typically also use a web framework like PHP or
ASP.NET, etc. With these frameworks you can communicate with a database for storing or
retrieving data.
34
6. The Web
• Internet (1960s)
• Google, 1998
• Facebook, 2004
• Smartphones, 2007
• Tablets, 2010
Microsoft:
Others:
• Eclipse
• Atom (free and open-source text and source code editor for macOS, Linux, and
Windows)
• Sublime
• Etc.
35
6. The Web
6.2 Client-Server
The basic principle of web is that it is a server and a client. The server hosts the web pages
and you request a web page from the client using a web browser.
36
6. The Web
37
6. The Web
The most common use of web servers is to host websites, but there are other uses such as
gaming, data storage or running enterprise applications.
38
6. The Web
Figure 6-9 shows some of the popular web browsers on the market today.
39
6. The Web
6.5 HTML
HTML, or HyperText Markup Language is the visual appearance of a web site. You could say
it is the language spoken by web browsers that makes it possible to see web contents in
your web browser. All web browser understands HTML. HTML 5 is the latest. HTML is
maintained by W3C - World Wide Web Consortium.
WYSIWYG – What You See Is What You Get. You don’t need to know HTML syntax - It’s just
like using MS Word.
40
6. The Web
Only possible to change the HTML source code and then select “Preview” in order to see
how it looks like in a Web Browser. You need to know HTML syntax.
• Visual Studio is not well suited for creating Static HTML Web Pages.
• Visual Studio is more optimized for creating Dynamic Web Pages and creating
ASP.NET Web Pages in special
Video:
HTML: https://youtu.be/DUEHx7l5a3Y
6.6 CSS
CSS – Cascading Style Sheets
CSS is used to control the style and layout of multiple web pages all at once
6.7 JavaScript
JavaScript is the de facto client-side programming language. Typically you want to use a
JavaScript Framework.
41
6. The Web
• JQuery
• TypeScript (Microsoft)
• PHP
6.8.1 PHP
PHP is a popular general-purpose scripting language that is especially suited to web
development.
PHP is a server-side scripting language for web development. It is used to make dynamic and
interactive web pages. PHP is an old and well-known technology, but it is still very popular
and easy to learn. PHP is open source (free) and cross-platform. Especially, the combination
of PHP and MySQL is a powerful combination used to create rich, dynamic web pages.
PHP is a server-side scripting language for web development. It is used to make dynamic
and interactive Web Pages
42
6. The Web
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
LAMP is popular when it comes to Web Programming. LAMP consists of the following
components:
All of these 4 components are open source, which is one of the reasons for its popularity.
PHP example:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Additional Training:
6.8.2 ASP.NET
ASP.NET is an open-source web framework, created by Microsoft, for building web apps and
services using the .NET Framework or the .NET Core. We have both ASP.NET and ASP.NET
Core. ASP.NET Core is the new approach built on .NET Core.
6.8.3 Django
Django is based on the Python programming language.
43
6. The Web
Python: https://www.halvorsen.blog/documents/programming/python/
• XML
• JSON
Today, JSON has become the dominating standard for data exchange.
6.9.1 XML
XML stands for eXtensible Markup Language.
XML was the dominating format for storing and exchanging data between a browser and a
server, but today JSON has taken over.
Additional Resources:
6.9.2 JSON
JSON: JavaScript Object Notation.
44
6. The Web
JSON is a syntax for storing and exchanging data. When exchanging data between a browser
and a server, the data can only be text. JSON is text.
Example:
Additional Resources:
45
7 HTML
HTML, or HyperText Markup Language is the visual appearance of a web site. You could say
it is the language spoken by web browsers that makes it possible to see web contents in
your web browser. All web browser understands HTML. HTML 5 is the latest. HTML is
maintained by W3C - World Wide Web Consortium.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
Content of the document......
</body>
</html>
Video:
HTML: https://youtu.be/DUEHx7l5a3Y
We can use Visual Studio because we already use it in our Project – and basic HTML syntax is
something you should know about.
Visual Studio is more optimized for creating Dynamic Web Pages and creating ASP.NET Web
Pages in special
For pure HTML pages, I recommend that you use Visual Studio Code instead
47
7. HTML
7.2.1 Title
Title:
<title>This is my Title</title>
7.2.2 Headers
Headers 1:
<h1>This is my Header</h1>
Header 2:
<h2>This is my Header</h2>
Header 3:
<h3>This is my Header</h3>
7.2.3 Paragraphs
Paragraphs:
<p>My first paragraph.</p>
7.2.4 Hyperlinks
Hyperlinks:
<!DOCTYPE html>
<html>
<body>
<h1>This is a heading</h1>
<a href="http://www.google.com">This is a link to Google</a>
</body>
</html>
7.2.5 Images
Images:
<!DOCTYPE html>
<html>
<body>
<h1>This is a heading</h1>
<img src= "myimage.jpg" alt=”blabla" width="104" height="142">
</body>
</html>
48
7. HTML
7.2.6 Tables
Tables:
<table width="200" border="1">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
<td>g</td>
<td>h</td>
</tr>
<tr>
<td>i</td>
<td>j</td>
<td>k</td>
<td>l</td>
</tr>
</table>
7.2.7 Comments
Comment:
<!-- Write your comments here -->
49
8 CSS
CSS is a stylesheet language that describes the presentation of an HTML page.
Use HTML to define the content of web pages, CSS is used to specify the layout of web
pages, while JavaScript is used to program the behavior of web pages.
CSS is used to control the style and layout of multiple web pages all at once
Basic Example:
body {
background-color: #d0e4fe;
}
h1 {
color: orange;
text-align: center;
}
p {
font-family: "Times New Roman";
font-size: 20px;
}
– An external style sheet is ideal when the style is applied to many pages. With
an external style sheet, you can change the look of an entire Web site by
changing just one file.
– An external style sheet can be written in any text editor. The file should not
contain any html tags.
– An internal style sheet should be used when a single document has a unique
style.
– You define internal styles in the head section of an HTML page, inside the
<style> tag
• Inline style
– An inline style loses many of the advantages of a style sheet (by mixing
content with presentation). Use this method sparingly!
myfile.html:
...
<head
...
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
..
</head>
...
8.2 Bootstrap
JavaScript/HTML, CSS Framework
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing
responsive, mobile-first websites.
Home Page:
https://getbootstrap.com
Bootstrap is a popular HTML, CSS, and JavaScript framework for developing responsive,
mobile first projects on the web
Bootstrap is a free and open-source front-end web framework for designing websites and
web applications.
51
8. CSS
It contains HTML- and CSS-based design templates for typography, forms, buttons,
navigation and other interface components, as well as optional JavaScript extensions.
Additional Training:
To use the Free Font Awesome 5 icons, you can choose to download the Font Awesome
library, or you can sign up for an account at Font Awesome and get a code (called KIT CODE)
to use when you add Font Awesome to your web page.
Additional Training:
52
9 JavaScript
JavaScript is the de facto client-side programming language. Typically, you want to use a
JavaScript Framework.
• JQuery
• TypeScript (Microsoft)
JavaScript is the default scripting language in all modern browsers, and in HTML5.
It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart
phones, and more.
Note that JavaScript and Java are different languages, both in concept and design.
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>
</body>
</html>
9.2 jQuery
jQuery is a JavaScript Library.
Additional Training:
54
9. JavaScript
9.3 AngularJS
JavaScript Framework developed by Google that has become very popular today.
55
10 Server-side Frameworks
We have many different so-called server-side frameworks for creating dynamic web pages:
• PHP
• Django
• ASP.NET
• Etc.
10.1 PHP
PHP is a server scripting language, and a powerful tool for making dynamic and interactive
Web pages.
10.2 Django
Django is based on the Python programming language.
Do you want to learn more about Python? Here you find lots of Python resources:
https://www.halvorsen.blog/documents/programming/python/
10.3 ASP.NET
ASP.NET is an open-source web framework, created by Microsoft, for building web apps and
services using the .NET Framework or the .NET Core. We have both ASP.NET and ASP.NET
Core. ASP.NET Core is the new approach built on .NET Core.
ASP.NET Core will be the main topic in this document. In this textbook we will go through
ASP.NET Core in detail. In Part 4: ASP.NET Core we start creating ASP.NET Core Web
Applications.
We have:
• ASP.NET Core MVC (Model-View Controller). If you are familiar with the MVC
approach, this could be your choice.
• ASP.NET Core with Razor Pages. This is the latest and recommended way. This has
become the "default" approach for ASP.NET today. It mixes the best from all the
others combined with PHP like syntax (PHP is probably the most popular Web
Framework today)
This textbook will focus on this latest and newest approach, namely ASP.NET Core with
Razor Pages.
• Program.cs – This file contains the entry point for the program.
• wwwroot folder - Contains static files, such as Images, HTML files, JavaScript files,
and CSS files.
• Pages folder – Here you are supposed to put your ASP.NET (".cshtml") web pages
In addition, it is standard to have a folder called “Models”. This folder contains C# classes
that takes care of the data. The data can, e.g., be a database or a file, e.g., a JSON file.
In addition, we have what we call Supporting files. Supporting files have names that begin
with an underscore (_).
• _Layout.cshtml file configures UI elements common to all pages. You can use this file
to set up the navigation menu at the top of the page
11.1 Resources
Here are some important ASP.NET Core resources:
59
11. Introduction to ASP.NET Core
60
11. Introduction to ASP.NET Core
61
11. Introduction to ASP.NET Core
62
11. Introduction to ASP.NET Core
63
11. Introduction to ASP.NET Core
Code:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Hello World</h1>
</div>
Video:
64
11. Introduction to ASP.NET Core
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor
Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C#
expressions and renders them in the HTML output.
This outputs the current date and time in the browser window.
65
11. Introduction to ASP.NET Core
Code:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Hello World</h1>
</div>
<div>
The current time is: @DateTime.Now
</div>
66
11. Introduction to ASP.NET Core
Index.cshtml.cs:
67
11. Introduction to ASP.NET Core
68
11. Introduction to ASP.NET Core
69
11. Introduction to ASP.NET Core
Example:
public void OnGet()
{
bookId = Convert.ToInt16(Request.Query["bookid"]);
connectionString =
_configuration.GetConnectionString("ConnectionString");
In this example the URL in the web browser could look something like this
https://BookApp/EditBook?bookid=4
70
11. Introduction to ASP.NET Core
If we want to send more than one variable, we use &, for example:
https://BookApp/EditBook?bookid=4&booktitle=Python&author=hamsun
Example
public void OnPost()
{
Book book = new Book();
book.BookId = Convert.ToInt16(Request.Form["bookId"]);
book.Title = Request.Form["bookTitle"];
book.Isbn = Request.Form["bookIsbn"];
book.PublisherName = Request.Form["bookPublisher"];
book.AuthorName = Request.Form["bookAuthor"];
book.CategoryName = Request.Form["bookCategory"];
connectionString =
_configuration.GetConnectionString("ConnectionString");
book.EditBook(connectionString, book);
Response.Redirect("./Books");
}
71
11. Introduction to ASP.NET Core
HTML Code:
<form name="bookForm" id="bookForm" method="post">
Title:
<br />
<input name="bookTitle" type="text" class="form-control
input-lg" autofocus required />
<br />
ISBN:
<br />
<input name="bookIsbn" type="text" class="form-control
input-lg" required />
<br />
Publisher:
<br />
<input name="bookPublisher" type="text" class="form-control
input-lg" required />
<br />
Author:
<br />
<input name="bookAuthor" type="text" class="form-control
input-lg" required />
<br />
Category:
<br />
<input name="bookCategory" type="text" class="form-control
input-lg" required />
72
11. Introduction to ASP.NET Core
<br />
</form>
73
12 ASP.NET Core
Fundamentals
Figure 12-1 shows a typical Solution Explorer in a ASP.NET Core Web Application.
• wwroot
• Models
• Pages
In the wwwroot you should put files like CSS files (in the css folder), JavaScript files (in your
js folder), Images in your images folder. Different libraries like Bootstrap, JQuery, etc. should
be put in the lib folder.
• appsettings.json
• Program.cs
• Startup.cs
• _Layout.cshtml
The web root is the base path to public, non-code, static resource files, such as:
• Stylesheets (.css) – Here you should put your CSS style sheets
• JavaScript (.js) – Here you should put your JavaScript code files
• Images (.png, .jpg, etc.) – This is the folder where you should put all your images
Static files are only served by default from the web root directory (and sub-directories).
In Razor (.cshtml) files, the tilde-slash (~/) points to the web root. A path beginning with ~/ is
referred to as a virtual path.
75
12. ASP.NET Core Fundamentals
12.3 appsettings.json
This file contains configuration data, such as connection strings.
"ConnectionStrings": {
"ConnectionString": "DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx"
}
Inside “ConnectionStrings” you can have one or more connection strings, let say you have a
development database, a test database and a customer database. This makes it easy to
switch between different connection strings.
"ConnectionStrings": {
"DevelopmentDB": "DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx"
"TestDB": "DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx"
}
76
12. ASP.NET Core Fundamentals
Folder: ./Pages/Shared
12.4.1 Layout
The default layout file in ASP.NET Core is “_Layout.cshtml”. You can modify this file so it fits
the ways you want to present your files. This layout will by default be added to al your web
pages (.cshtml files).
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
77
12. ASP.NET Core Fundamentals
A “clean” (removing “everything”, just leave the minimum) _Layout.cshtml may look like
this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebApplication</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
If you don’t want to use the _Layout.cshtml on a specific file, set the following on top of
your .cshtml web page:
@{
Layout = "";
}
You can also have multiple Layout files. If you want to use another Layout file than the
default for a specific web page (.cshtml file), you can do something like this:
@{
Layout = "~/Pages/Shared/_Layout2.cshtml";
}
12.5 Models
In the Models folder you suppose to put your C# Classes. You don’t need to name this folder
Models, but that is the recommended name. In that way it will be easier to understand and
modify programs made by others.
78
12. ASP.NET Core Fundamentals
An ASP.NET Razor page has the “.cshtml” (e.g., “Index.cshtml”) file extension. This file
contains a mix of HTML and Razor syntax. The Razor syntax is actually C# code mixed
together with the HTML code.
The Razor parts of the file are executed on the web server before the page is sent to the
client (your web browser).
The Razor page may also have a C# code file linked to it, this file has the extension
“.cshtml.cs” (e.g., “Index.cshtml.cs”). The “.cshtml.cs” file is called the Page Model.
• A “.cshtml” file that contains HTML markup with C# code using Razor syntax.
• A “.cshtml.cs” (“code behind” or “Page model” file) file that contains C# code that
handles page events.
The default Razor page is Index.cshtml. But this can of course be changed if you want to.
When we create a new Razor page (e.g., “Test”) it will look like something like this:
Test.cshtml
@page
@model TestModel
@{
ViewData["Title"] = "Test Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>This is a Razor Page</p>
</div>
The Page Model file (Test.cshtml.cs) or “code behind” file will look something like this:
using System.Collections.Generic;
79
12. ASP.NET Core Fundamentals
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace DemoApp.Pages
{
public class TestModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
}
}
}
namespace DemoApp.Pages
{
public class TestModel : PageModel
{
public string name;
}
}
}
In this example we have declared a public variable. Then later we want to display the value
in our web page (Razor Page (.cshtml)).
80
12. ASP.NET Core Fundamentals
You typically put code that needs to run before the web page is sent to the client in the
OnGet() method.
<div class="text-center">
<h1 class="display-4">Welcome</h1>
</div>
As you see we need to use @Model.xxx where xxx is the name of a public variable in the
Page Model file.
81
12. ASP.NET Core Fundamentals
82
13 Razor
Razor is a markup syntax for embedding server-based code into webpages. The Razor syntax
consists of Razor markup, C#, and HTML. Files containing Razor generally have a .cshtml file
extension.
The default Razor language is HTML. Rendering HTML from Razor markup is no different
than rendering HTML from an HTML file. HTML markup in .cshtml Razor files is rendered by
the server unchanged.
Example:
@{
var number = 1;
}
The value of variables is rendered into HTML by prefixing them with the @ sign.
Example:
The number is @number
Example:
Example:
@{
var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
foreach(var number in numbers)
{
@number
}
}
Comments can be used in different ways, either // for a single line or /* */ for multiple lines.
Example:
// This is a comment
…
/* … */
/*
Multiple Lines
…
…
*/
13.2 Model
Using Model inside a foreach:
Example:
@foreach (var measurement in Model.measurementParameterList)
{
<tr>
<td> @measurement.MeasurementId</td>
<td> @measurement.MeasurementName</td>
<td> @measurement.MeasurementUnit</td>
</tr>
84
13. Razor
85
Part 5 Database
Communication
All modern applications typically communicate with a Database System. Here we will
introduce Database Systems in general and especially Microsoft SQL Server. Then we will
cover Database Communication with C# and ASP.NET Core in combination with SQL Server
from Microsoft.
• SQL Server
• MySQL
• MariaDB
• Etc.
Figure 14-1: ER diagram with Primary Keys and Foreign Keys relationships
SQL Server consists of a Database Engine and a Management Studio (and lots of other stuff
which we will not mention here). The Database engine has no graphical interface - it is just a
service running in the background of your computer (preferable on the server). The
Management Studio is graphical tool for configuring and viewing the information in the
database. It can be installed on the server or on the client (or both).
Videos:
88
14. Database Systems
It is quite simple to create a new database in Microsoft SQL Server. Just right-click on the
“Databases” node and select “New Database…”
89
14. Database Systems
There are lots of settings you may set regarding your database, but the only information you
must fill in is the name of your database:
You may also use the SQL language to create a new database, but sometimes it is easier to
just use the built-in features in the Management Studio.
In order to make a new SQL query, select the “New Query” button from the Toolbar.
90
14. Database Systems
Here we can write any kind of queries that is supported by the SQL language.
• INSERT
• SELECT
• UPDATE
• DELETE
91
14. Database Systems
The Data Manipulation Language (DML) is the subset of SQL used to add, update and delete
data.
The acronym CRUD refers to all of the major functions that need to be implemented in a
relational database application to consider it complete. Each letter in the acronym can be
mapped to a standard SQL statement:
Additional Resources:
14.2.1 Tables
In Figure 14-7 we see an example of some tables for a university or a school. These tables
store information regarding the students, the teacher, the courses, the grades, etc.
92
14. Database Systems
Here are some “Best practice” recommendations for creating tables in a database system:
• Tables: Use upper case and singular form in table names – not plural, e.g.,
“STUDENT” (not students)
• Columns: Use Pascal notation, e.g., “StudentId”
• Primary Keys:
– If the table name is “COURSE”, name the Primary Key column “CourseId”, etc.
– “Always” use Integer and Identity(1,1) for Primary Keys
• Specify Required Columns (NOT NULL) – i.e., which columns that need to have data
or not
• Data Types: Standardize on these Data Types: int, float, varchar(x), datetime, bit
• Use English for table and column names
• Avoid abbreviations! (Use RoomNumber – not RoomNo, RoomNr, ...)
We want to create a table called “CUSTOMER” which has the following columns and data
types:
93
14. Database Systems
Typically, you also want to sue a tool for modelling the database, e.g., Erwin.
Primary keys:
As you see we use the “Primary Key” keyword to specify that a column should be the
Primary Key.
If you use the Designer tools in SQL Server, you can easily set the primary Key in a table just
by right-click and select “Set primary Key”.
94
14. Database Systems
The primary Key column will then have a small key in front to illustrate that this column is
a Primary Key.
Foreign Keys:
Example:
SCHOOL:
CREATE TABLE SCHOOL
(
SchoolId int IDENTITY(1,1) PRIMARY KEY,
SchoolName varchar(50) NOT NULL UNIQUE,
95
14. Database Systems
CLASS:
CREATE TABLE CLASS
(
ClassId int IDENTITY(1,1) PRIMARY KEY,
SchoolId int NOT NULL FOREIGN KEY REFERENCES SCHOOL (SchoolId),
ClassName varchar(50) NOT NULL UNIQUE,
Description varchar(1000) NULL,
)
GO
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
The FOREIGN KEY constraint also prevents that invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the table it points
to.
If you want to use the designer, right-click on the column that you want to be the Foreign
Key and select “Relationships…”:
96
14. Database Systems
Click on the “Add” button and then click on the small “…” button. Then the following
window pops up (Tables and Columns):
Here you specify the primary Key Column in the Primary Key table and the Foreign Key
Column in the Foreign Key table.
97
14. Database Systems
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you
cannot insert a new record or update a record without adding a value to this field.
We see that “CustomerNumber”, “LastName” and “FirstName” is set to “NOT NULL”, this
means these columns needs to contain data. While “AreaCode”, “Address” and “Phone”
may be left empty, i.e, they don’t need to be filled out.
In the Table Designer you can easily set which columns that should allow NULL or not:
UNIQUE:
98
14. Database Systems
The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and
PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns.
Note! You can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
We see that the “CustomerNumber” is set to UNIQUE, meaning each customer must have a
unique Customer Number. Example:
If you want to use the designer, right-click on the column that you want to be UNIQUE and
select “Indexes/Keys…”:
99
14. Database Systems
Then click “Add” and then set the “Is Unique” property to “Yes”:
Very often we would like the value of the primary key field to be created automatically
every time a new record is inserted.
Example:
CREATE TABLE CUSTOMER
(
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
AreaCode int NULL,
Address varchar(50) NULL,
100
14. Database Systems
As shown below, we use the IDENTITY() for this. IDENTITY(1,1) means the first value will be 1
and then it will increment by 1.
We can use the designer tools to specify that a Primary Key should be an identity column
that is automatically generated by the system when we insert data in to the table.
Click on the column in the designer and go into the Column Properties window:
14.2.2 Views
Views are virtual table for easier access to data stored in multiple tables.
101
14. Database Systems
Example:
We use the SCHOOL and CLASS tables as an example for our View. We want to create a View
that lists all the existing schools and the belonging classes.
102
14. Database Systems
SELECT
SCHOOL.SchoolName,
CLASS.ClassName
FROM
SCHOOL
INNER JOIN CLASS ON SCHOOL.SchoolId = CLASS.SchoolId
Note! In order to get information from more than one table, we need to link the tables
together using a JOIN.
103
14. Database Systems
14.2.4 Triggers
A database trigger is code that is automatically executed in response to certain events on a
particular table in a database.
104
15 ADO.NET
ADO.NET is the core data access technology for .NET languages.
The great thing about this is that you can use the same C# code either you are creating a
desktop application or a web application.
Typically, you put your C# database code in one or more classes, and those will then be the
same either you are creating a desktop application (which has direct access to the database)
or a web application. If your database does not have direct access to the database (the
database is e.g., located on the internet), you can create and use a so-called Web API (also
called Web Service or REST API). The Web API will then be the middleware between the
desktop application and the database server.
You install these packages using the NuGet Package Manager, see Figure 15-1.
There are many ways and methods we can use to retrieve data from a database. Here we
will focus on something called ADO.NET. ADO.NET can use different so-called Data
Providers. We will use “System.Data.SqlClient”. This will be demonstrated in the Demo
Application below.
The entire example can be downloaded from the home page of this textbook.
16.1.1 Database
In order to create this ASP.NET Core example we need to create a simple database that
consists of a single table called “MEASUREMENT”.
We start by creating the Database in SQL Server Management Studio (Figure 16-2).
Then we create necessary table. We can either create the tables directly using the Table
designer in the SQL Server Management Studio (not shown here) or we can open/create a
SQL script that inserts the table (Figure 16-3).
107
16. Data from Database
Next, we need to create some initial data into the table. We can either create the data
directly using the editor (right-click on the table in the Object Explorer and select “Edit Top
200 Rows”) in the SQL Server Management Studio (See Figure 16-4) or we can open/create a
SQL script that inserts the necessary data (not shown here).
Figure 16-4: Inserting Data manually from SQL Server Management Studio
108
16. Data from Database
Next you need to configure your Project (Figure 16-6) by writing the name. for the project,
where it should be located on your hard drive, etc.
109
16. Data from Database
In the next window (see Figure 16-7) you need to select the proper template. We select the
“Web Application” template.
110
16. Data from Database
Select “Create” in Figure 16-7 and the Visual studio Project will be created based on your
choices. See Figure 16-8.
As you see from Figure 16-8, the following Folders and Files have been created:
• Program.cs – This file contains the entry point for the program.
• wwwroot folder - Contains static files, such as HTML files, JavaScript files, and CSS
files.
• Pages folder – Here you are supposed to put your ASP.NET (".cshtml") web pages
In addition, it is standard to have a folder called “Models”. This folder contains C# classes
that takes care of the data. The data can, e.g., be a database or a file, e.g., a JSON file.
In addition, we have what we call Supporting files. Supporting files have names that begin
with an underscore (_).
111
16. Data from Database
• _Layout.cshtml file configures UI elements common to all pages. You can use this file
to set up the navigation menu at the top of the page
In the Pages folder some default Razor pages have been created, like “Index.cshtml”, etc.
The “Index.cshtml” file is typically the startup file for your web application, but if you want
you can configure this in the Startup.cs file.
Let’s run the application and see if the application can be run inside your web browser. See
Figure 16-9.
112
16. Data from Database
Now we need to start creating the necessary code for our application.
Let’s start to create a Models folder where we are making our Class that do the retrieving of
data from the database. See Figure 16-10. (In the example I have written Model instead of
Models, bit that’s the same)
113
16. Data from Database
Then we create a Class called, e.g., “Measurements.cs” in the Models (Model) folder. See
Figure 16-11.
114
16. Data from Database
namespace MeasurementApp.Model
{
public class Measurement
{
public int MeasurementId { get; set; }
public string MeasurementName { get; set; }
public string MeasurementUnit { get; set; }
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
115
16. Data from Database
if (dr != null)
{
while (dr.Read())
{
Measurement measurmentParameter = new Measurement();
measurmentParameter.MeasurementId =
Convert.ToInt32(dr["MeasurementId"]);
measurmentParameter.MeasurementName =
dr["MeasurementName"].ToString();
measurmentParameter.MeasurementUnit = dr["Unit"].ToString();
measurementParameterList.Add(measurmentParameter);
}
}
return measurementParameterList;
}
}
}
As you see the connection string to the database is hardcoded inside the
“Measurement”class:
string connectionString = "DATA SOURCE=xxx;UID=sa;PWD=xxx;DATABASE=MEASUREMENTDB";
Just replace the “xxx” with the settings for your database.
Make sure to install the necessary NuGet package(s). See Figure 16-13. We need the
System.Data.SqlClient.
Figure 16-13: Make sure the necessary NuGet packages are installed
Then we create our Razor File in the “Pages” folder. Let’s name the file
“Measurement.cshtml”. Make sure to select Razor Page (a Razor Page with a Page Model).
See Figure 16-14.
116
16. Data from Database
A code behind file, also called the Page Model will also be created automatically. See Figure
16-15.
117
16. Data from Database
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MeasurementApp.Model;
namespace MeasurementApp.Pages
{
public class MeasurementModel : PageModel
{
measurementParameterList = measurement.GetMeasurmentParameters();
}
}
}
Then we can make the contents of the “Measurement.cshtml” file. See Figure 16-16.
<div>
118
16. Data from Database
<h1>Measurement Parameters</h1>
Below you see all the Measurement Names registered in the Database:
<table class="table">
<thead>
<tr>
<th>MeasurementId</th>
<th>Measurement Name</th>
<th>Unit</th>
</tr>
</thead>
<tbody>
@foreach (var measurement in Model.measurementParameterList)
{
<tr>
<td> @measurement.MeasurementId</td>
<td> @measurement.MeasurementName</td>
<td> @measurement.MeasurementUnit</td>
</tr>
}
</tbody>
</table>
</div>
@xxx is the Razor code. The Razor code is executed on the server before the web page is
sent to the client (web browser).
The “Model.” variable is used to retrieve data from the Page Model file
(“Measurement.cshtml.cs”). All public variables that are created in the Measurement.cshtml
.cs file are available in the Measurement.cshtml file by using @Model.<variablename>.
Now, our application should be finished. Let’s run the application in our web browser. See
Figure 16-17.
119
16. Data from Database
where you replaced the “xxx” with the settings for your database.
The user “sa” (System Administrator) is the default user. You can use that one for testing,
but for your final application you should setup and use another user.
16.2.1 appSettings.json
A better solution is to put the connection string inside the “appSettings.json” which is
meant for storing configuration data, such as connection strings, etc.
Let us start by putting the connection string into the “appSettings.json” file:
120
16. Data from Database
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "DATA SOURCE=xxx;UID=sa;PWD=xxx;DATABASE=MEASUREMENTDB "
}
where you replace the “xxx” with the settings for your database.
namespace MeasurementApp.Model
{
public class Measurement
{
public int MeasurementId { get; set; }
public string MeasurementName { get; set; }
public string MeasurementUnit { get; set; }
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
Measurement measurmentParameter = new Measurement();
measurmentParameter.MeasurementId =
Convert.ToInt32(dr["MeasurementId"]);
measurmentParameter.MeasurementName =
dr["MeasurementName"].ToString();
measurmentParameter.MeasurementUnit = dr["Unit"].ToString();
measurementParameterList.Add(measurmentParameter);
}
}
return measurementParameterList;
}
}
121
16. Data from Database
services.AddSingleton<IConfiguration>(Configuration);
}
We have added:
services.AddSingleton<IConfiguration>(Configuration);
namespace MeasurementApp.Pages
{
public class MeasurementModel : PageModel
{
readonly IConfiguration _configuration;
connectionString =
_configuration.GetConnectionString("ConnectionString");
measurementParameterList =
measurement.GetMeasurmentParameters(connectionString);
}
}
}
Now we can run the application. The result should be the same as before, see Figure 16-17.
122
17 CRUD Applications
CRUS is short for:
Create
Read
Update
Delete
The acronym CRUD refers to all the major functions that are implemented for
communication with a database.
We will show how we can use ASP.NET Core to get (read, retrieve, select) data from the
database, insert data into the database, update the data inside the database and deleting
data inside the database.
The entire example can be downloaded from the home page of this textbook.
This example can be the foundation for all types of applications. All web applications
typically show some data from the database in a list or table, then you will typically have
features for add new data, edit/update existing data or delete data.
When I start on a new development project, I just use this application as a template or as a
foundation for my new web application.
124
17 CRUD Applications
125
17 CRUD Applications
126
17 CRUD Applications
17.1.2 Database
We will use the following tables:
AUTHOR:
if not exists (select * from dbo.sysobjects where id =
object_id(N'[AUTHOR]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [AUTHOR]
(
[AuthorId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[AuthorName] [varchar](50) NOT NULL UNIQUE,
[Address] [varchar](50) NULL,
[Phone] [varchar](50) NULL,
[PostCode] [varchar](50) NULL,
[PostAddress] [varchar](50) NULL,
)
GO
PUBLISHER:
if not exists (select * from dbo.sysobjects where id =
object_id(N'[PUBLISHER]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [PUBLISHER]
(
[PublisherId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
127
17 CRUD Applications
CATEGORY:
if not exists (select * from dbo.sysobjects where id =
object_id(N'[CATEGORY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [CATEGORY]
(
[CategoryId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[CategoryName] [varchar](50) NOT NULL UNIQUE,
[Description] [varchar](1000) NULL,
)
GO
BOOK:
if not exists (select * from dbo.sysobjects where id = object_id(N'[BOOK]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [BOOK]
(
[BookId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[Title] [varchar](50) NOT NULL UNIQUE,
[ISBN] [varchar](20) NOT NULL,
[PublisherId] [int] NOT NULL FOREIGN KEY REFERENCES [PUBLISHER] ([PublisherId]),
[AuthorId] [int] NOT NULL FOREIGN KEY REFERENCES [AUTHOR] ([AuthorId]),
[CategoryId] [int] NOT NULL FOREIGN KEY REFERENCES [CATEGORY] ([CategoryId]),
[Description] [varchar](1000) NULL,
[Year] [date] NULL,
[Edition] [int] NULL,
[AverageRating] [float] NULL,
)
GO
128
17 CRUD Applications
“GetBookData” View:
CREATE VIEW GetBookData
AS
SELECT
BOOK.BookId,
BOOK.Title,
BOOK.ISBN,
PUBLISHER.PublisherName,
AUTHOR.AuthorName,
CATEGORY.CategoryName
FROM BOOK
INNER JOIN AUTHOR ON BOOK.AuthorId = AUTHOR.AuthorId
INNER JOIN PUBLISHER ON BOOK.PublisherId = PUBLISHER.PublisherId
INNER JOIN CATEGORY ON BOOK.CategoryId = CATEGORY.CategoryId
GO
129
17 CRUD Applications
130