Core (1 2 3)
Core (1 2 3)
NET Core
2023
Abdullah Hoolif
What is Asp.Net Core?
ASP.NET Core is a free, open-source, and cloud-optimized framework that can run on Windows, Linux,
or macOS. You can say it is the new version of ASP.NET. The framework is a complete rewrite from
scratch in order to make it open-source, modular, and cross-platform.
ASP.NET Core:
-> Open-Source
-> Cross-Platform
-> Modular
console
desktop
web
mobile
cloud, etc…
History of ASP.NET
As we know, ASP.NET is the framework that has been used to develop data-driven web applications
for many years. Since then, the ASP.NET Framework went through a steady evolutionary change, and
finally, the most decent evolution is ASP.NET Core.
The ASP.NET Core is not a continuous part of the ASP.NET 4.x Framework. Instead, it is a completely
new framework.
This Framework is an actual re-write of the current ASP.NET 4.x Framework, but with much smaller
and a lot more modular.
Some people think that many things remain the same, but that is not completely true. The ASP.NET
Core is actually a big fundamental change to the ASP.NET Framework.
.NET Core Characteristics:
Open-source Framework: .NET Core is framework maintained by Microsoft and available on
GitHub under MIT and Apache 2 Licenses. You can view, download, or contribute to the source
code using the following GitHub repositories:
Consistent across Architecture: Execute the code with the same behavior in different instruction set
architectures, including x64, x86, and ARM.
Wide range of Applications: Various types of applications can be developed and run on .NET Core platforms
such as Console, Desktop, Web, Mobile, Cloud, IoT, ML, Microservices, Gaming, etc…
Support Multiple Languages: You can use C#, F#, and Visual Basic programming to develop .
Modular Architecture: .NET Core supports a modular architecture approach using NuGet Packages. There are
different NuGet Packages available for various features that can be added to the .
Conn .NET Core Characteristics:
CLI Support: Using CLI commands you can develop and run .NET applications as well as you can
also publish the application using CLI command.
IoC Container: One of the most important used design patterns in the real-time application is the
Dependency Injection Design Pattern. It includes the built-in IoC (Inversion of Control) container for
automatic dependency injection which makes it maintainable and testable
Unified MVC and Web API Framework:
The ASP.NET Core provides a unified programming model for developing both Web
apps and Web APIs. That means a single controller class can be used to handle both.
The Controller we create in ASP.NET Core (either Web APPs or Web APIs)
In the ASP.NET Core Web API application, the controller action method is going to
return JsonResult. At the same time if it is an ASP.NET Core Web application, then the
return type of the controller action method is going to be ViewResult.
Testing and Maintainability:
You can easily test and maintain the applications developed using the ASP.NET Core MVC framework. This is
possible because it allows you to separate different parts of your application into independent pieces and it
also allows you to test them independently. The Testing frameworks such as xUnit and MOQ can be easily
integrated into ASP.NET Core MVC application for simulating any scenario.
Integration with Modern UI Framework: It allows you to use and manage modern UI frameworks such as
AngularJS/Angular, React JS, and Bootstrap, etc
Handling Request and Response Pipeline:
We can handle the request and response in the ASP.NET Core application by using the new
Middleware Components. In earlier ASP.NET 4.x we generally use Handlers and Modules to handle
the Request and Response pipeline. The ASP.NET Core Framework provides a lot of built-in
Middleware Components and we can use those Middleware Components to handle the request and
response pipeline.
Hosting:
ASP.NET Core web application can be hosted on multiple platforms with any web server such as IIS,
Apache, etc… It is not dependent only on IIS as a standard .NET Framework.
Code Sharing: It allows you to build a class library that can be used with .NET Frameworks such as
.NET Framework 4.x or Mono. Thus, a single code base can be shared across frameworks.
Side-by-Side App Versioning: ASP.NET Core runs in .NET Core, which supports the simultaneous
running of multiple versions of applications.
Extensible Framework:
The ASP.NET Core MVC Framework is designed to be highly extensible. That means you
can create an application today, that can be extended to any levels in the future. Some of the
key features provided by this framework that give it the extensible power are as follows.
1. View Components
2. Tag Helpers
3. Routing
Language Support:
Dot Net Core Framework supports the following language i.e. using the following languages you can develop
.NET Core applications. We are going to use C# as the programming language in this course.
1. C#
2. F#
3. Visual Basic (VB)
https://dotnet.microsoft.com/download
ASP.NET Core Project File
Creating ASP.NET Core Web Application
The Kestrel is the cross-platform web server for the ASP.NET Core application. That means
this Server supports all the platforms and versions that the ASP.NET Core supports. By
default, it is included as the internal web server in the .NET Core application.
Before using the Kestrel server to run our application, let us first open the launchSettings.json file which is
present inside the Properties folder of your application. Once you open the launchSettings.json file you will find
the following code by default.
.NET Core Command-Line Interface
The .NET Core command-line interface (CLI) is a new cross-platform tool for creating,
restoring packages, building, running and publishing .NET applications.
We created our first ASP.NET Core application using Visual Studio in the previous chapter.
Visual Studio internally uses this CLI to restore, build and publish an application. Other higher
level IDEs, editors and tools can use CLI to support .NET Core applications.
The .NET Core CLI is installed with .NET Core SDK for selected platforms. So we don't need to
install it separately on the development machine.
How to run a .NET Core application using .NET
Core CLI?
We can also run the ASP.NET Core application from the command line using the .NET Core CLI. The CLI stands for
Command Line Interface.
When we run an ASP.NET Core application using the .NET Core CLI, then the .NET Core runtime uses Kestrel as the
webserver. We will discuss the .NET Core CLI in detail in our upcoming article. Now, let us see how to run a dot net core
application using .NET Core CLI Command.
First. open the command prompt and type “dotnet —” and press enter as shown below.
Once you change the directory to your project folder, then execute the “dotnet run” command as shown in the below
image.
Basic Commands
● new
● restore
● build
● publish
● run
● migrate
● Clean
● List
● help
● watch
Application Types:
Model :The Model is the component in the MVC Design pattern which is used to manage that data .
View: The view component in the MVC Design pattern is used to contain the logic to represent the model
data as a user interface with which the end-user can interact. Basically, the view is used to render the
domain data
xuseen
Actions are the methods in controller class which are responsible for returning the
view or Json data. Action will mainly have return type “ActionResult”
following categories:
EmptyResult represents an ActionResult that when executed will do nothing. We can use it when we want to
return empty result.
JsonResult
JsonResult formats the given object as JSON. JsonResult is use to return JSON-formatted data,
● public JsonResult JsonResult()
● {
● var name = "Farhan Ahmed";
● return Json(new { data=name});
● }
JsonResult formats the given object as JSON. JsonResult is use to return JSON-formatted data, it returns
JSON regardless of what format is requested through Accept header.
ViewResult
ActionResult
ActionResult is the base class of all the result type action method.
ViewResult represents an ActionResult that renders a view to the response. It is used to render a view to
response, we use it when we want to render a simple .cshtml view.
● Entity Framework (EF) Core is an ORM (Object-Relational Mapper) Framework for data access in .Net. It
was released along with .NET Core and is an extensible, lightweight, Open Source, and cross-platform
version of Entity Framework data access technology. It works on multiple operating systems like
Windows, Mac, and Linus.
What is ORM?
● The term ORM stands for Object-Relational Mapper and it automatically creates classes
based on database tables and the vice versa is also true. That is, it can also generate the
necessary SQL to create the database based on the classes.
● As a developer, we mostly work with the application business objects and the ORM
Framework generates the necessary SQL (to perform the CRUD operation) that the
underlying database can understand. So, in simple words, we can say that the ORM
Framework eliminates the need for most of the data access code that as a developer we
generally write.
Why do we need to use an ORM?
● Let us understand why we need to use the ORM Framework with an example.
● Suppose we want to develop an application to manage the students of a college. In order to do this, we
may need to create classes such as Student, Department, Address, etc. Technically we called these
classes as Domain classes.
● Without using ORM Framework like Entity Framework or EF Core, we have to write lots of data access
code to perform the CRUD operations i.e. store and retrieve the Student, Department and Address data
from the underlying database tables.
● For example, in order to perform CRUD operations i.e. read, insert, update or delete from a database
table, we generally need to write custom code in our application to generate the required SQL
statements which can be understood by the underlying database. Again, when we want to read the data
from the database into our application, then also we have to write some custom code to map the
database data to our model classes like Student, Department, Address, etc. This is a very common task as
a developer for us that we do almost in every application.
● An ORM Framework like Entity framework or EF Core can do all of the above for us and saves a lot of
time if we provide the necessary required information to the ORM Framework. The ORM Framework sits
between our application code and the Database. It eliminates the need for most of the custom
data-access code that we usually write without an ORM.
Cont..
EF Core Development Approaches:
● Entity Framework Core supports two development approaches. They are as follows:
● Code-First Approach
● Database-First Approach
● EF Core mainly targets the code-first approach and provides little support for the database-first
approach at the moment.
● Out of the box, in the code-first approach, the EF Core API creates the database and tables
using migration based on the default conventions and configuration. If you want then you
can also change the default conventions used to create the database and its related tables.
This approach is useful in Domain-Driven Design (DDD).
EF Core Database First Approach:
● If you have an existing database and database tables are already there, then you need to
use the EF Core Database First Approach. In the database-first approach, the EF Core
creates the DBContext and Domain classes based on the existing database schema using EF
Core Command.
EF Core Database Providers:
● The EF Core supports both relational and non-relational databases and this is possible due
to database providers. The database providers are available as NuGet packages. The
Database Provider sits between the EF Core and the database it supports.
Required Packages
DbContext in Entity Framework Core
● What is a DbContext class?
● The DBContext class is basically used by our application to interact with the underlying database.
That means this class is used to manage the database connection as well as also used to perform
CRUD operation with the underlying database.
● How to create and use the DbContext class in Entity Framework Core?
● In order to use the DbContext class in your application, you need to create a class derives from
the DbContext class. The DbContext class present is
in Microsoft.EntityFrameworkCore namespace.
Cont..
● The DbContext in Entity Framework Core perform the following tasks:
● Manage database connection
● Configure model & relationship
● Querying database
● Saving data to the database
● Configure change tracking
● Caching
● Transaction management
●
●
● The DbContext
}
public DbSet<Students> students { get; set; }
App setting —
"ConnectionStrings": {
"dbcon": "Server=.;database=testdb;Trusted_Connection=True;TrustServerCertificate=True;"
}
Controller
1. private readonly StudetsDBContext _context;
2.
3. public usersController(StudetsDBContext context)
4. {
5. _context = context;
6. }
7. —-----------------
8. Index
9. public IActionResult Index()
10. {
11. var students=_db.students.ToList();
12.
13. return View(students);
14. }
15.
16.
Index
Conn
public IActionResult Details(int id)
{
var students = _db.students.Find(id);
return View(students);
}
—-------------------
public IActionResult Create()
{
return View();
}
—-------------
[HttpPost]
public IActionResult Create(Students students)
{
_db.students.Add(students);
_db.SaveChanges();
return RedirectToAction("Index");
}
In the Create
View
Edit
return View(students);
}
[HttpPost]
public IActionResult Delete(Students students)
{
_db.students.Remove(students);
_db.SaveChanges();
return RedirectToAction("Index");
}
What is ViewBag in ASP.NET Core MVC?
ViewBag is a dynamic property of the Controller base class. The dynamic type is introduced in C#
4.0. It is very much similar to the var keyword that means we can store any type of value in it but the
type will be decided at run time rather than compile-time.
The ViewBag :transfers the data from the controller action method to a view only, the reverse
is not possible.
How to Pass and Retrieve data From ViewBag in ASP.NET Core MVC?
The point that you need to keep in mind is, ViewBag is operating on the dynamic data type. So we don’t
require typecasting while accessing the data from a ViewBag. It does not matter whether the data that we
are accessing is of type string or any complex type.
ViewBag in ASP.NET Core MVC with String
Type:
ViewData in ASP.NET Core MVC Application
The ViewData in ASP.NET Core MVC is a dictionary of weakly typed objects which is derived from the
ViewDataDictionary class.
1. ViewData is used to pass the data from the controller action method to a view and we can
display this data on the view.
2. The ViewData is work on the principle of Key-value pairs. This type of binding is known as
loosely binding.
3. We can pass any type of data in ViewData like normal integer, string, even though you can
pass objects.
4. ViewData uses the ViewDataDictionary type.
How to use ViewData?
First, we need to create a new key in ViewData and then assign some data to it. The
key should be in string format and you can give any name to it and then you can
assign any data to this key.
Since ViewData is a server-side code, hence to use it on view, we need to use the
razor syntax i.e. @
@ViewData[“KeyName”]
DataAnnotations
is used to configure your model classes, which will highlight the most commonly
needed configurations.
Data annotation in ASP.NET Core refers to the process of labeling the data that an
application deal with.
In other words, data annotations are attributes that are added to the properties which
will let you enforce data input restrictions that might be necessary
System.ComponentModel.DataAnnotations
includes
the following attributes that impacts the nullability or size of the column.
Key
Required
MinLength
MaxLength
StringLength
Timestamp
ConcurrencyCheck