Use the SQLite database provider with EF Core

In the previous unit, you learned how to persist data to an in-memory database. Persisting data to an in-memory database is useful in development. But, because all data is lost when the application is restarted, it isn’t suitable for production. In production, you should persist data to a database like SQL Server, MySQL, PostgreSQL, or SQLite.

Database providers abstract database access from the application code

One of the benefits of performing database access through an abstraction layer like Entity Framework (EF) Core is that it decouples your application from the database provider. You can change the database provider without rewriting your database access code. You shouldn’t expect to be able to switch database providers without any effect to your application code, but the changes will be minimized and localized.

A related advantage of using EF Core is that you can reuse your code, experience, and data access libraries to work with any other EF Core database provider.

For this tutorial, you’ll use, but you might also use one that works better for you. EF Core currently supports more than 20.

Steps to add a new database provider

In general, you’ll use the following steps to implement a new database provider:

  1. Add one or more NuGet packages to your project to include the database provider.
  2. Configure the database connection.
  3. Configure the database provider in the ASP.NET Core services.
  4. Perform database migrations.

In the next unit, you’ll walk through the steps to add the SQLite database provider. Similar steps will apply for other database providers.

aws training courses malaysia

What is Entity Framework Core?

Most nontrivial web applications need to reliably run operations on data, such as create, read, update, and delete (CRUD). They also need to persist any changes made by these operations between application restarts. Although there are various options for persisting data in .NET applications, Entity Framework (EF) Core is a user-friendly solution and a great fit for many .NET applications.

Understand EF Core

EF Core is a lightweight, extensible, open source, and cross-platform data access technology for .NET applications.

EF Core can serve as an object-relational mapper, which:

  • Enables .NET developers to work with a database by using .NET objects.
  • Eliminates the need for most of the data-access code that typically needs to be written.

EF Core supports a large number of popular databases, including SQLite, MySQL, PostgreSQL, Oracle, and Microsoft SQL Server.

The model

With EF Core, data access is performed by using a model. A model is made up of entity classes and a context object that represents a session with the database. The context object allows querying and saving data.

The entity class

In this scenario, you’re implementing a pizza store management API, so you use a Pizza entity class. The pizzas in your store have a name and a description. They also need an ID to allow the API and database to identify them. The Pizza entity class that you use in your application identifies pizzas:

C#Copy

namespace PizzaStore.Models 
{
  public class Pizza
  {
      public int Id { get; set; }
      public string? Name { get; set; }
      public string? Description { get; set; }
  }
}

The context class

This application has only one entity class, but most applications have multiple entity classes. The context class is responsible for querying and saving data to your entity classes, and for creating and managing the database connection.

Perform CRUD operations with EF Core

After EF Core is configured, you can use it to perform CRUD operations on your entity classes. Then, you can develop against C# classes, delegating the database operations to the context class. Database providers in turn translate it to database-specific query language. An example is SQL for a relational database. Queries are always executed against the database, even if the entities returned in the result already exist in the context.

Query data

The context object exposes a collection class for each entity type. In the preceding example, the context class exposes a collection of Pizza objects as Pizzas. Given that we have an instance of the context class, you can query the database for all pizzas:

C#Copy

var pizzas = await db.Pizzas.ToListAsync();

Insert data

You can use the same context object to insert a new pizza:

C#Copy

await db.pizzas.AddAsync(
    new Pizza { ID = 1, Name = "Pepperoni", Description = "The classic pepperoni pizza" });

Delete data

Delete operations are simple. They require only an ID of the item to be deleted:

C#Copy

var pizza = await db.pizzas.FindAsync(id);
if (pizza is null)
{
    //Handle error
}
db.pizzas.Remove(pizza);

Update data

Similarly, you can update an existing pizza:

C#Copy

int id = 1;
var updatepizza = new Pizza { Name = "Pineapple", Description = "Ummmm?" };
var pizza = await db.pizzas.FindAsync(id);
if (pizza is null)
{
    //Handle error
}
pizza.Description = updatepizza.Description;
pizza.Name = updatepizza.Name;
await db.SaveChangesAsync();

Use the EF Core in-memory database

EF Core includes an in-memory database provider that can be used to test your application. The in-memory database provider is useful for testing and development, but it shouldn’t be used in production. In the next unit, you’ll use the in-memory database provider to create a database and perform CRUD operations on it.

azure training courses malaysia

Introduction

When you build a web application that deals with data, you’ll most likely want to store that data in a database. Fortunately, minimal APIs built on ASP.NET Core can be easily integrated with a large variety of databases by using Entity Framework (EF) Core.

Scenario: Build a prototype

You’re a developer on a team. You’ve built an API that handles create, read, update, and delete (CRUD) operations on a table of data. You plan to build a front-end application that uses that API. You want to store the data in a database so that you can use the data in your front-end application.

What will you learn?

You’ll learn how to use EF Core to persist your data, first to an in-memory database and then into SQLite. You’ll also learn how to use the EF Core to query the database.

What is the main goal?

Add database support to your minimal API application.

big data hadoop training courses malaysia

Use a database with minimal API, Entity Framework Core, and ASP.NET Core

Learn how to add a database to a minimal API application.

Learning objectives

In this module, you will:

  • Learn how to add Entity Framework Core to a minimal API application.
  • Persist data to an in-memory datastore.
  • Persist data to a SQLite database.

Prerequisites

  • Familiarity with .NET
  • A basic understanding of what an API is

blockchain training courses malaysia

Publish .NET apps

Coding an app with ASP.NET Core is different from designing a static website with HTML, CSS, and JavaScript. A static website can be deployed to any web server that supports static files. The web server doesn’t need to process static files; it simply serves them over HTTP. When a web browser requests a resource, the web server simply sends the file back to the browser.

An ASP.NET Core app, on the other hand, is a dynamic web application. It runs as a program on the web server. When the user’s web browser sends a request to the web server, the web server runs the app to generate a response, and then the web server sends the response back to the browser.

Publishing a .NET app is the process of preparing the app for deployment on a server. When you publish a .NET app, you package your app and its dependencies into a folder that can be easily deployed. The published app doesn’t include any source code files, but it does include all the files needed to run the app, including the compiled assemblies (DLLs), configuration files, and any other assets your app needs. The app can then be deployed to a web server, cloud service, or other hosting environment.

Types of deployments

When you publish a .NET app, you can choose between two different types of deployments: framework-dependent and self-contained. The type of deployment you choose affects how your app is packaged and deployed.

Framework-dependent deployment

An animation showing how a framework-dependent deployment depends on the presence of the .NET runtime on the target machine.

A framework-dependent deployment includes only your app’s files and dependencies. It doesn’t include the .NET runtime. Instead, the target machine must have the .NET runtime installed in order to run the app. This type of deployment is the default for .NET apps.

Self-contained deployment

An animation showing how a self-contained deployment includes the .NET runtime with the app.

A self-contained deployment includes your app’s files, dependencies, and the .NET runtime. The .NET runtime is included with the app, so the target machine doesn’t need to have the .NET runtime installed in order to run the app. Including the runtime makes self-contained deployments larger than framework-dependent deployments, but it also makes them more portable. It also makes it easier to run multiple versions of the .NET runtime side by side on the same machine.

Choosing a deployment type

The deployment type you choose depends on your app’s requirements and the target environment. Consider the following factors when choosing a deployment type:

Deployment Type

Advantages

Disadvantages

Framework-dependent

  • Smaller deployment size
  • Faster deployment times
  • Uses the .NET runtime installed on the target machine, regardless of operating system
  • Requires the .NET runtime to be installed on the target machine
  • Requires managing the .NET runtime versions installed on the target machine

Self-contained

  • No need to install .NET runtime on the target machine
  • Easier to run multiple versions of .NET side by side
  • Larger deployment size
  • Slower deployment times
  • .NET runtime updates must be deployed with the app

Where to deploy your app

Once you’ve published your app, you can deploy it to any environment that supports ASP.NET Core. Here are a few options:

Kestrel

By default, ASP.NET Core apps run in ASP.NET Core’s built-in web server, Kestrel. Kestrel is cross-platform and tuned for high performance. It supports all modern web server features, including HTTPS, HTTP/2, HTTP/3, and WebSockets. It’s also customizable and extensible, so you can configure it to meet your app’s needs. Kestrel is the recommended web server for ASP.NET Core apps.

Since Kestrel is built into ASP.NET Core, you can deploy your app to any machine capable of running .NET, including Windows, macOS, and Linux. Kestrel works great by itself, but apps running on Kestrel are often deployed behind a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. The reverse proxy server handles incoming requests from the internet and forwards them to Kestrel. This allows you to take advantage of the reverse proxy server’s features, such as load balancing, caching, and SSL termination.

Internet Information Services (IIS)

If you’re deploying to Windows, you can host your ASP.NET Core app in IIS. To do this, you need to install the ASP.NET Core Module for IIS. The module forwards requests from IIS to Kestrel, which runs your app. This allows you to take advantage of IIS’s features, such as process management, logging, and security.

Containers

If you’re deploying to a containerized environment, you can package your ASP.NET Core app as a Docker container. This allows you to run your app in any container runtime that supports Docker, such as Docker Desktop, Docker Enterprise, or Kubernetes. Containers are portable and scalable, so you can run your app on any machine that supports Docker, regardless of the underlying operating system.

Azure

If you’re deploying to Azure, you can host your ASP.NET Core app in Azure App Service or Azure Container Apps. Various tools make it easy to deploy your app to Azure from the command line. These tools include:

  • Azure Tools extension for Visual Studio Code
  • Visual Studio
  • Azure CLI
  • Azure Developer CLI (azd)

ibm aix system i training courses malaysia

Introduction

An ASP.NET Core app is composed of source code files, static assets, and configuration files. When you build an ASP.NET Core app, the source code is compiled into an executable form that can be run with the .NET runtime. Publishing an ASP.NET Core app is the process of packaging the executable app into a form that can be deployed and run on a server.

Example scenario

Suppose you’re an entry-level ASP.NET Core developer at a small company. Your manager tasked you with developing a new web application for the company’s customers and deploying it to a web server.

What will we be doing?

In this module, you’ll use the .NET SDK to create a boilerplate ASP.NET Core web application. After ensuring it runs correctly, you’ll publish the app in two different ways: as a framework-dependent deployment and as a self-contained deployment. Finally, you’ll learn about the different ways to deploy an ASP.NET Core app to Azure.

What is the main goal?

By the end of this module, you’ll be able to build and publish an ASP.NET Core app for deployment. You’ll also be able to describe the different methods to deploy an ASP.NET Core app to Azure.

ibm cognos bi training courses malaysia

Publish an ASP.NET Core app

Publish an ASP.NET Core app using the .NET CLI. Describe the difference between framework-dependent and self-contained deployments. Understand deploying an ASP.NET Core app to Azure.

Learning objectives

By the end of this module, you’ll be able to:

  • Describe some of the deployment options available for ASP.NET Core apps.
  • Describe what the dotnet publish command does.
  • Publish an ASP.NET Core app as a framework-dependent deployment.
  • Publish an ASP.NET Core app as a self-contained deployment.

Prerequisites

  • Ability to write C# and Razor code at a beginner level.
  • Ability to use the .NET CLI at a beginner level.
  • Latest .NET SDK installed.
  • Visual Studio Code installed with the following extensions:
    • C# Dev Kit
    • Azure Tools (optional)
  • An Azure subscription (optional).

ibm informix training courses malaysia

Discover Razor syntax

Razor is a markup syntax for embedding .NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Razor syntax is similar to the templating engines of various JavaScript single-page application (SPA) frameworks, such as Angular, React, VueJs, and Svelte.

The default Razor language is HTML. Rendering HTML from Razor markup is no different than rendering HTML from an HTML file. The server renders HTML markup in .cshtml Razor files unchanged.

Razor syntax

Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output.

When an @ symbol is followed by a Razor reserved keyword, it transitions into Razor-specific markup. Otherwise, it transitions into plain HTML. To escape an @ symbol in Razor markup, use a second @ symbol. The following code sample would render the value of @Username in the HTML output.

SyntaxOutput
<p>@Username</p>Renders the value of @Username in the HTML output.
<p>@@Username</p>Renders “@Username” in the HTML output.

HTML attributes and content containing email addresses don’t treat the @ symbol as a transition character. For example, the email addresses in the following code are untouched by Razor parsing:

HTMLCopy

<a href="mailto:Support@contoso.com">Support@contoso.com</a>

Add code to a page using the @ character

The following code examples show how the @ character can be used to implement inline expressions, single statement blocks, and multi-statement blocks:

HTMLCopy

<!-- Single statement blocks  -->
@{ var myMessage = "Hello World"; }

<!-- Inline expressions -->
<p>The value of myMessage is: @myMessage</p>

<!-- Multi-statement block -->
@{
    var greeting = "Welcome to our site!";
    var weekDay = DateTime.Now.DayOfWeek;
    var greetingMessage = greeting + " Today is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>

The following code sample shows how to use a combination of .NET code and HTML to create the body of a table from a data model. The @foreachstatement iterates through the Model.FruitModels data model and generates a table row containing the fruit name and if it’s available.

razorCopy

@* Code is truncated for readability. *@
<tbody>
    @foreach (var obj in _fruitList ?? [])
    {
        <tr>
            <td>@obj.name</td>
            <td>@obj.instock</td>
        </tr>
    }
</tbody>

ibm infosphere datastage training courses malaysia

Explore Blazor render modes and component lifecycle

Blazor is a .NET frontend web framework that supports both server-side rendering and client interactivity in a single programming model:

  • Create rich interactive UIs using C#.
  • Share server-side and client-side app logic written in .NET.
  • Render the UI as HTML and CSS for wide browser support, including mobile browsers.
  • Build hybrid desktop and mobile apps with .NET and Blazor.

Components

Blazor apps are based on components. A component in Blazor is an element of UI, such as a page, dialog, or data entry form. Components are .NET C# classes built into that

  • Define flexible UI rendering logic.
  • Handle user events.
  • Can be nested and reused.
  • Can be shared and distributed as Razor class libraries or NuGet packages.

The component class is written in the form of a Razor markup page with a .razor file extension. Components in Blazor are formally referred to as Razor components, informally as Blazor components. Razor is a syntax for combining HTML markup with C# code.

Static and interactive rendering concepts

Razor components are either statically rendered or interactively rendered:

  • Static or static rendering is a server-side scenario where the component is rendered without interplay between the user and .NET/C# code. JavaScript and HTML DOM events remain unaffected, but no user events on the client can be processed with .NET running on the server.
  • Interactive or interactive rendering means that the component has the capacity to process .NET events via C# code. The .NET events are processed on the server in the ASP.NET Core runtime, or in the browser on the client in the WebAssembly-based Blazor runtime.

Client and server rendering concepts

Activity that takes place on the user’s system is said to occur on the client or client-side. Activity that takes place on a server is said to occur on the server or server-side. The term rendering means to produce the HTML markup that browsers display.

  • Client-side rendering (CSR) means that the final HTML markup is generated by the .NET WebAssembly runtime on the client. No HTML for the app’s client-generated UI is sent from a server to the client for this type of rendering. User interactivity with the page is assumed.
  • Server-side rendering (SSR) means that the final HTML markup is generated by the ASP.NET Core runtime on the server. The HTML is sent to the client over a network for display by the client’s browser. No HTML for the app’s server-generated UI is created in the client for this type of rendering. SSR can be of two varieties:
    • Static SSR: The server produces static HTML that doesn’t provide for us interactivity or maintaining Razor component state.
    • Interactive SSR: Blazor events permit user interactivity and the Blazor framework maintains the component state.
  • Prerendering is the process of initially rendering page content on the server without enabling event handlers for rendered controls. The server outputs the HTML UI of the page as soon as possible in response to the initial request, which makes the app feel more responsive to users.

Render modes

Every component in a Blazor Web App adopts a render mode to determine the hosting model it uses, where it’s rendered, and if it’s interactive.

The following table shows the available render modes for rendering Razor components in a Blazor Web App.

NameDescriptionRender locationInteractive
Static ServerStatic server-side rendering (static SSR)ServerNo
Interactive WebAssemblyClient-side rendering (CSR) using Blazor WebAssembly.ClientYes
Interactive AutoInteractive SSR using Blazor Server initially and then CSR on subsequent visits after the Blazor bundle is downloaded.Server, then clientYes
Interactive ServerInteractive server-side rendering (interactive SSR) using Blazor Server.ServerYes

Enable support for interactive render modes

A Blazor Web App must be configured to support interactive render modes. The following extensions are automatically applied to apps created from the Blazor Web App project template during app creation. Individual components are still required to declare their render mode, per the previous Render modes section, after the component services and endpoints are configured in the app’s Program file.

Services for Razor components are added by calling AddRazorComponents. The following Program file example adds services and configuration for enabling interactive SSR:

C#Copy

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

Apply a render mode to a component instance

To apply a render mode to a component instance use the @rendermode Razor directive attribute where the component is used. In the following example, interactive server-side rendering (interactive SSR) is applied to the Dialog component instance:

C#Copy

<Dialog @rendermode="InteractiveServer" />

Lifecycle events

The Blazor component lifecycle consists of several methods that allow developers to execute code at specific points during a component’s lifecycle. The lifecycle methods can be overridden to perform other operations in components during component initialization and rendering. Here are the key lifecycle methods:

  • OnInitialized / OnInitializedAsync: Called when the component is initialized. It’s a good place to perform any setup work for the component.
  • OnParametersSet / OnParametersSetAsync: Called each time the component’s parameters are set. This can happen after the component is first initialized or when the parent component re-renders and passes new parameters.
  • OnAfterRender / OnAfterRenderAsync: Called after the component finishes rendering. It’s a good place to perform any post-rendering logic, such as interacting with JavaScript.
  • ShouldRender: Called to determine whether the component should re-render. By default, it returns true, but you can override it to return false if you want to prevent the component from re-rendering.
  • Dispose / DisposeAsync: Called when the component is being disposed of. It’s a good place to release any resources that the component is holding onto.

These lifecycle methods provide a structured way to manage the state and behavior of Blazor components throughout their lifecycle.

ibm lotus notes domino datastage training courses malaysia

Introduction

Blazor is a .NET frontend web framework that supports both server-side rendering and client interactivity in a single programming model.

Learning objectives

After completing this module, you’ll be able to:

  • Combine HTML and C# to define dynamic page rendering logic
  • Render API responses in Blazor Web apps
  • Create pages that perform HTTP operations

ibm websphere training courses malaysia