European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core 9.0 Hosting - HostForLIFE :: Knowing the .NET Entity Framework

clock July 28, 2025 07:06 by author Peter

What is Entity Framework?
Microsoft's ORM tool for.NET is called Entity Framework (EF). Instead of writing SQL queries directly, it enables developers to use C# objects to carry out database actions. Depending on whether we begin with code, a database, or a visual model, Entity Framework supports three primary database development approaches. Depending on the needs of the project, each strategy works in a different setting. Consider a library system, where EF manages the backend conversion of this object-oriented query into SQL.

You have classes like Book, Author, and Borrower.
Instead of writing SQL to fetch books, you just query the context.Books.Where(b => b.Author == "John").

A simple understanding of the differences between code and database.

Code (C#) Database (SQL)
Class → Table
Property → Column
Object (instance) → Row

EF Core 8, which includes.NET 8, is the most recent and stable version of Entity Framework as of 2025. It is excellent for real-world projects since it is more powerful, faster, and provides long-term support. In addition to supporting cloud databases like Azure SQL, EF Core 8 is compatible with other well-known databases, including SQL Server, PostgreSQL, SQLite, and MySQL. Because it facilitates cross-platform development, you can use it to create applications for Linux, macOS, and Windows. The Data Access Layer (DAL) of a layered.NET architecture uses Entity Framework (EF) to manage all database interactions. It enables developers to interact with C# objects rather than writing SQL queries directly, creating a clear division between data operations and business logic.

What is ORM (Object-Relational Mapping)?
ORM stands for Object-Relational Mapping. It is a programming technique that lets developers interact with a relational database (like SQL Server, MySQL, PostgreSQL) using the object-oriented paradigm (like C# or Java classes) without manually writing SQL queries for every operation.
ORM maps database tables to programming language classes and table rows to objects, so we can work with the database like working with regular code objects. ORM is like an interpreter that lets your code "talk" to the database in its own language — while you stay in your comfort zone of writing C#.

Imagine we have an Excel sheet (database) with rows and columns. Each row represents a record. Now think of C# classes as templates that match the structure of those rows. So instead of writing.
SELECT *
FROM Products
WHERE Price > 100;


With ORM (like Entity Framework), we can simply write.
var products = dbContext.Products
    .Where(p => p.Price > 100)
    .ToList();

The ORM converts that C# code into SQL behind the scenes and gets the data for us. Using an ORM offers several benefits; it avoids writing repetitive SQL code, keeps the application code cleaner and more readable, supports LINQ-based querying for more natural data access in C#, automatically maps foreign keys and relationships between tables, and makes the codebase easier to maintain, update, and test over time.

Entity Framework (EF) Approaches

Entity Framework supports three main development approaches for working with databases, depending on whether you start with code, a database, or a visual model. Each approach suits different scenarios based on project needs.

1. Code First Approach
In Code First, we start by writing C# classes that represent our data model. EF then creates the database schema based on these classes. Best suited for new projects where no existing database is present.

Use Cases: Provides complete control over the database schema through code, allowing the structure to be defined using C# classes. Ideal for scenarios that require continuous development and updates, as it supports easy schema evolution using migrations. Imagine we're building a Library Management System from scratch. We define classes like Book, Author, and Borrower in code.
public class Book {
public int Id { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
}


EF uses these classes to generate tables like Books and Authors in the database.

2. Database First Approach
In the Database First method, we begin with an existing database, and Entity Framework then reverse-engineers the schema and generates the corresponding C# classes and DbContext.

Use Cases: Ideal for legacy systems or enterprise applications where the database is already created and maintained independently. This approach allows quick integration by generating the required entity classes and context directly from the existing schema, saving development time and ensuring consistency between the application and the established database structure. Imagine We're joining a team maintaining a Retail Inventory System. The SQL Server database already contains tables like Products, Suppliers, StockLevels, and PurchaseOrders, all designed and managed by a database administrator. Instead of manually recreating models, we use EF Core’s Scaffold-DbContext command to generate the entity classes and context.
dotnet ef dbcontext scaffold "DBConnectionString" Microsoft.EntityFrameworkCore.SqlServer

Now we can query context. Products or context.PurchaseOrders using LINQ, without writing SQL manually.

3. Model First Approach (EF6 only)
In Model First, we design our data model visually using the EF Designer (.edmx file). EF then generates both the database and the C# code.

Use Case: Suitable for visual-first development and rapid prototyping scenarios where the data model is designed using a graphical interface. This approach allows quick creation and modification of the model through a visual designer. It is only supported in Entity Framework 6 and is not available in EF Core. Imagine a Hospital Management System, where entities like Patient, Doctor, and Appointment are visually modeled with defined relationships.

Each appointment is linked to one patient and one doctor.
Doctors and patients can have multiple appointments.

In the Model First workflow using Entity Framework 6, development begins by opening the EF Designer within Visual Studio. Inside this design surface, entities such as Patient, Doctor, or Appointment are visually arranged to represent the intended data model. Relationships between entities are then defined, for example, linking appointments to both patients and doctors to establish clear entity interactions. Once the model is structured and all associations are in place, Entity Framework generates both the underlying SQL database schema and the C# codebase directly from the visual design, streamlining the transition from concept to implementation.

Why and When to Use Entity Framework (EF)?
Simplifies Data Access: EF allows working with databases using C# classes and LINQ instead of writing raw SQL, making development faster and easier.
Object-Relational Mapping (ORM): EF maps database tables to C# classes and rows to objects, providing a smooth object-oriented experience with relational data.
Ideal for CRUD Applications: EF is perfect for applications that need to perform Create, Read, Update, and Delete operations on structured data.
Supports Migrations and Versioning: EF (especially Code First) helps manage database schema changes over time using migrations, which is essential for agile development.
Available as a NuGet Package: EF is not built-in by default; it is available as a NuGet package, allowing you to install only what you need, such as Microsoft.EntityFrameworkCore for EF Core. If you're learning more about NuGet packages, read the full article at: https://www.c-sharpcorner.com/article/nuget-package-manager-in-net/

Conclusion
As my understanding goes, Entity Framework (EF) is a powerful and flexible ORM that simplifies data access in .NET applications. It allows developers to work with databases using C# code instead of raw SQL, making development faster, cleaner, and more maintainable. With different approaches like Code First, Database First, and Model First, EF supports a wide range of scenarios—from new projects to legacy systems. Whether building web apps, desktop software, or APIs, EF—especially EF Core—is a modern and efficient choice for building data-driven applications.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Real time Example of Constructor Chaining

clock July 24, 2025 09:26 by author Peter

A constructor is a unique kind of function that is invoked automatically when a class instance is created. Static constructors are initialized by static members of a class, while constructors overload numerous constructor procedures within a class. Constructors has no return type and will be declared by the compiler if it is not defined.

Calling one constructor from another is known as constructor chaining. This procedure cuts down on repetition and reuses code. There are two syntactic options employing the chaining procedure, which are listed below.

Make use of the base class's constructor.

public ClassName() : base() { }

Call another constructor in the same class.
public ClassName() : this() { }

Real-time examples for constructor chaining with BankAccount class constructors are given here. Constructor overloading concept will be used to call the same class constructor by using 'this' keyword.
class BankAccount {
    String accountHolder;
    String accountType;
    double balance;

    // Default constructor
    public BankAccount() {
        this("Unknown", "Savings", 0.0); // Constructor chaining
    }

    // Constructor with accountHolder
    public BankAccount(String accountHolder) {
        this(accountHolder, "Savings", 0.0); // Constructor chaining
    }

    // Constructor with accountHolder and accountType
    public BankAccount(String accountHolder, String accountType) {
        this(accountHolder, accountType, 0.0); // Constructor chaining
    }

    // Full constructor
    public BankAccount(String accountHolder, String accountType, double balance) {
        this.accountHolder = accountHolder;
        this.accountType = accountType;
        this.balance = balance;
    }

    public void displayDetails() {
        System.out.println("Account Holder: " + accountHolder);
        System.out.println("Account Type: " + accountType);
        System.out.println("Balance: " + balance);
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount();
        BankAccount account2 = new BankAccount("aaa");
        BankAccount account3 = new BankAccount("bbb", "Current");
        BankAccount account4 = new BankAccount("cccc", "Savings", 5000.0);

        account1.displayDetails();
        account2.displayDetails();
        account3.displayDetails();
        account4.displayDetails();
    }
}


Output
Account Holder: Unknown
Account Type: Savings
Balance: 0.0

Account Holder: aaa
Account Type: Savings
Balance: 0.0

Account Holder: bbb
Account Type: Current
Balance: 0.0

Account Holder: cccc
Account Type: Savings
Balance: 5000.0



European ASP.NET Core 9.0 Hosting - HostForLIFE :: New Features in.NET 10: Quantum Security & JSON Updates

clock July 21, 2025 09:05 by author Peter

The .NET libraries have seen significant enhancements with Microsoft's.NET 10 Preview 6 release, which focuses on security, accuracy, and cryptographic innovation. The capabilities in this preview add more control and future-proof security options to your development toolbox, whether you're working with JSON data interchange or investigating sophisticated cryptographic techniques.

In this article, we’ll dive into the key updates in Preview 6.

  • Disallowing duplicate JSON properties
  • Enforcing strict JSON serialization
  • Introduction of Post-Quantum Cryptography (PQC) support

Option to Disallow Duplicate JSON Properties
Duplicate JSON keys have historically been a gray area in JSON parsers. The JSON specification doesn’t mandate a standard behavior for duplicate properties, which can result in unpredictable runtime behavior and even security vulnerabilities.

Why does it matter?
In scenarios where malicious users could manipulate JSON payloads, duplicate properties could be used to override expected values, posing a serious security risk.

New Feature
The new AllowDuplicateProperties flag in JsonSerializerOptions and JsonDocumentOptions can now be set to false, ensuring that duplicate properties throw exceptions, improving both security and consistency.

Example
string json = """{ "Value": 1, "Value": -1 }""";
Console.WriteLine(JsonSerializer.Deserialize<MyRecord>(json).Value); // Output: -1 (last one wins)
// Enabling strict duplicate checks
JsonSerializerOptions options = new() { AllowDuplicateProperties = false };
// These will now throw JsonException
JsonSerializer.Deserialize<MyRecord>(json, options);
JsonSerializer.Deserialize<JsonObject>(json, options);
JsonSerializer.Deserialize<Dictionary<string, int>>(json, options);
JsonDocumentOptions docOptions = new() { AllowDuplicateProperties = false };
JsonDocument.Parse(json, docOptions); // Throws JsonException
record MyRecord(int Value);


Strict JSON Serialization Options
By default, the JSON serializer in .NET is designed to be flexible, but sometimes too flexible for high-security or precision-critical applications.
Introducing JsonSerializerOptions.Strict

A new strict preset configuration enables best practices automatically, including.

  • Disallowing unmapped members
  • Disabling duplicate properties
  • Enforcing case-sensitive property matching
  • Respecting nullable annotations and required constructor parameters

This preset helps enforce strict contracts between your models and incoming JSON.

Use Case Example
string validJson = """{ "Name": "Alice", "Age": 30 }""";
var person = JsonSerializer.Deserialize<Person>(validJson, strictOptions);

record Person(string Name, int Age);

Use this when deserialization must exactly match your schema, with no surprises.

Post-Quantum Cryptography (PQC)
As the threat of quantum computing becomes more real, cryptographic standards are evolving. Microsoft is proactively addressing this with Post-Quantum Cryptography (PQC) support.

With .NET 10 Preview 6, support for PQC is being introduced through the Windows CNG (Cryptography Next Generation) platform. This enables the use of quantum-resistant algorithms in your .NET applications.

Sample: Verifying a PQC Digital Signature
using System;
using System.IO;
using System.Security.Cryptography;

private static bool ValidateMLDsaSignature(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature,

string publicKeyPath)
{
    string publicKeyPem = File.ReadAllText(publicKeyPath);
    using (MLDsa key = MLDsa.ImportFromPem(publicKeyPem))
    {
        return key.VerifyData(data, signature);
    }
}


Note. This works on Windows Insider builds with PQC support (Canary Channel).
Microsoft is also working on down-level support for the .NET Framework via the Microsoft.Bcl.Cryptography package, helping legacy apps move toward quantum-safe cryptography.

Conclusion

.NET 10 Preview 6 is more than just an incremental update, it is laying the foundation for secure, resilient, and precise applications. From safer JSON parsing to next-generation cryptographic capabilities, this release reflects Microsoft’s focus on developer security and interoperability.

Try It Out

You can start testing these features today using the .NET 10 Preview 6 SDK. If you’re a library author, security-focused developer, or someone handling sensitive data contracts, these updates are for you.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Examples to Help You Understand Dependency Injection (DI) in.NET Core

clock July 15, 2025 10:08 by author Peter

Dependency Injection (DI): What is it?
A design pattern called Dependency Injection (DI) is used to accomplish loose coupling between classes and their dependencies. Dependencies are injected from the outside, typically by a framework like.NET Core, rather than being created by a class itself. This encourages improved modularity, testability, and maintainability in application design.

Why Use DI?
Improves testability (easily mock dependencies)
Enhances flexibility and maintainability

Supports SOLID principles, especially:

  • Inversion of Control (IoC)
  • Single Responsibility Principle

How DI Works in .NET Core?
.NET Core comes with a built-in IoC container that supports three main service lifetimes:

Lifetime Description Example Use Case
Singleton One instance for the entire application Caching, config, loggers
Scoped One instance per HTTP request User/session-level services
Transient New instance every time it's requested Lightweight, stateless logic

Step-by-Step Example: Injecting a Service
1. Define an Interface

public interface IMessageService
{
    string GetMessage();
}


2. Create a Concrete Implementation
public class HelloMessageService : IMessageService
{
    public string GetMessage()
    {
        return "Hello from DI!";
    }
}


3. Register the Service in the Program.cs (.NET 6+)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IMessageService, HelloMessageService>(); // DI registration


4. Inject the Service in a Controller
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    private readonly IMessageService _messageService;

    public HomeController(IMessageService messageService)
    {
        _messageService = messageService;
    }

    [HttpGet]
    public string Get() => _messageService.GetMessage();
}


Output
GET /home
=> "Hello from DI!"
Real-World Use Case

In a recent project, we used DI to inject:

  • ILoggingService
  • IEmailService
  • IUserRepository

This allowed us to easily swap implementations during unit testing and to mock external services such as SendGrid and SQL Server, enabling a much more testable and scalable architecture.

Summary

  • DI is built into .NET Core via IServiceCollection.
  • Encourages clean, testable, and modular code.
  • Supports different service lifetimes (Singleton, Scoped, Transient).
  • Use constructor injection as the standard approach.


European ASP.NET Core 9.0 Hosting - HostForLIFE :: Microsoft Entra External ID Integration with Blazor Web Application

clock July 11, 2025 08:58 by author Peter

Managing external user IDs becomes crucial as businesses provide more digital services to clients, partners, and outside developers. By offering a standards-based, scalable, and safe identification solution that works well with contemporary apps, Microsoft Entra External ID assists in overcoming this difficulty. 

 This article will demonstrate how to combine an ASP.NET Core MVC application with Microsoft Entra External ID. Setting up authentication, managing user claims, and enforcing authorization for external users will all be covered. This article will assist you in implementing identity management, whether you're creating a secure, user-friendly application or a multi-tenant SaaS platform.

Get started with Integration
Step 1. Open Visual Studio 2022, click on Create a New Project, select ASP.NET Core Web App (MVC) Template, provide a project name, and click Next to get a wizard below.

Step 2. In the service dependencies wizard, add the dotnet misidentify tool to add a Microsoft identity platform, and click Next

Step 3. Select the tenant and click Create New to register a new External Entra ID application or select an existing application,  as shown in the figure below.

Step 4. The next step is to add Microsoft Graph or any other API. For a demo, I'm just going to skip this process.
Finally, click next; it will scaffold all required NuGet packages and changes in the Program.cs, appsettings.json

Step 5. In this step, switch to entra.microsoft.com and ensure you are in the External ID tenant, go to the user flow. Please refer to my article to check how to create a user flow. Select the user flow and click on Application to link our application to the user flow, as shown in the figures below.


Step 6. Finally, run the application. It will display the Microsoft Entra External ID user flow sign-in screen. Sign in using your social account credentials. After successful authentication, the application will navigate to the Home screen.

Summary
A detailed tutorial on how to integrate Microsoft Entra External ID with an ASP.NET Core MVC application has been shown to us. It clarifies key ideas including maintaining user claims, implementing secure access controls, and configuring authentication for external users. Developers may improve application security and offer a smooth experience for external partners, clients, and vendors by leveraging Microsoft's identity platform. The manual supports identity management's strategic strategy as well as its technical implementation.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: LINQ and Data View in C# and VB.NET

clock July 8, 2025 07:29 by author Peter

Here, a base class example and an exploration of Data View and LINQ (Language-Integrated Query) using DataTable Query for retrieving unique values from the database will be provided. LINQ is compatible with the most recent version,.NET 9, as well as.NET Core 3.1,.NET 5, and.NET 6. We will retrieve the data from a DataTable to a DataView using an example of a Book Class. Below is an example of a model-based class.

Book.cs
public class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

Book Class Output Example without using LINQ.

BookID Title Author Genre Price
1 XXX xxx 1.1 45.00
2 YYY yyy 2.1 45.00
3 ZZZZ zzz 1.1 50.00
4 AAA aaa 1.1 30.00

To retrieve the unique values of the version sorted by price value, the example code below is provided for C# and VB.NET.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Book> books = new List<Book>
        {
            new Book { BookID = 1, Title = "XXX", Author = "xxx", version = "1.1", Price = 45.00m },
            new Book { BookID = 2, Title = "YYY", Author = "yyy", version = "2.1", Price = 50.00m },
            new Book { BookID = 3, Title = "ZZZZ Hobbit", Author = "zz", version = "1.1", Price = 30.00m },
            new Book { BookID = 4, Title = "AAA", Author = "aa", version = "1.1", Price = 42.00m }
        };

        // LINQ: Get all 1.1 books sorted by price
        var programmingBooks = books
            .Where(b => b.version == "1.1")
            .OrderBy(b => b.Price);

        Console.WriteLine("Books (sorted by price):");
        foreach (var book in programmingBooks)
        {
            Console.WriteLine($"{book.Title} by {book.Author} - ${book.Price}");
        }
    }
}

class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string version { get; set; }
    public decimal Price { get; set; }
}

Dim bookTable As New DataTable()
bookTable.Columns.Add("BookID", GetType(Integer))
bookTable.Columns.Add("Title", GetType(String))
bookTable.Columns.Add("Author", GetType(String))
bookTable.Columns.Add("Genre", GetType(String))
bookTable.Columns.Add("Price", GetType(Decimal))

' Sample data
bookTable.Rows.Add(1, "XXX", "xxx", "1.1", 45.0D)
bookTable.Rows.Add(2, "YYY", "yyy", "1.2", 45.0D)
bookTable.Rows.Add(3, "ZZZ", "zzz", "2.1", 50.0D)
bookTable.Rows.Add(4, "AAA", "aa", "1.1", 30.0D)

Dim view As New DataView(bookTable)
Dim distinctBooks As DataTable = view.ToTable(True, "Title", "Author")

For Each row As DataRow In distinctBooks.Rows
    Console.WriteLine($"Title: {row("Title")}, Author: {row("Author")}")
Next

Output
Title: XXX, Author: xxx
Title: ZZZZ, Author: zz
Title: AAA, Author: aa



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in