Entity Framework Core (EF Core).

Entity Framework Core (EF Core) is a modern, lightweight, and extensible version of the Entity Framework, which is an Object-Relational Mapper (ORM) for .NET applications. It allows developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers usually need to write. Below, we will explore the key concepts of EF Core, including the Code-First approach, DbContext and DbSet, migrations, the repository pattern and unit of work, and LINQ queries with async operations.

What is Entity Framework Core?

Entity Framework Core (EF Core) is a modern, lightweight, open-source Object-Relational Mapper (ORM) for .NET. It allows developers to interact with databases using C# objects, eliminating the need to write most raw SQL queries.

🧠 Think of EF Core as a bridge between your C# code and the SQL database.

Key Features of EF Core

  • Cross-platform: Works on Windows, Linux, macOS
  • LINQ support: Query databases using C# syntax
  • Change tracking: Tracks changes in objects to update the DB
  • Migrations: Manage schema changes via code
  • Lazy/Eager/Explicit Loading: Controls how related data is loaded
  • Concurrency Handling: Manages data conflicts in multi-user apps

There are two types of Entity Framework Core approaches that we follow to interact with the database.
  • Database First Approach.
  • Code First Approach.

What is the Code-First Approach?

In the Code-First approach, you define your database schema using C# classes, and EF Core generates the database from this code. You don’t need an existing database instead you start with code, then create and update the database using migrations.

How Code-First Works:

Step 1: Create C# classes to represent tables (called entities).
Step 2: Create a DbContext class to manage the database connection and sets.
Step 3: Configure EF Core in Program.cs.
Step 4: Use Migrations to generate the schema and apply it to the database.

Step-by-Step Example of Code-First Approach.

Step 1. Install EF Core NuGet Packages.

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 2. Define Your Entity (Model)
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class Product
{
    [Key]                                // Defines primary key
    public int Id { get; set; }

    [Required]                           // NOT NULL
    [MaxLength(100)]                     // Max length for Name
    public string Name { get; set; }

    [Column(TypeName = "decimal(10,2)")] // Define precision for Price
    [Range(0, 99999.99)]                 // Validation range
    public decimal Price { get; set; }

    [Required]
    [DefaultValue(true)]                 // Default value
    public bool IsAvailable { get; set; } = true;
}

In Entity Framework Core, you can define constraints using Data Annotations (attributes on properties).

Step 3: Create a DbContext.
public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
}

This is your custom database context class, and it's a key part of using Entity Framework Core (EF Core) with the Code-First approach.
EF Core uses this class to:
  • Configure the connection to the database
  • Map your C# models (like Product) to database tables
  • Track changes and execute queries
  • Save data to the database
DbContext is the core class in EF Core that manages all database operations (querying, saving, updating, etc.).

DbSet<Product> tells EF Core: “I want a table called Products in the database, and each row will be a Product object.”

Step 4: Register the DbContext in Program.cs.
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
And in appSettings.json
"ConnectionStrings": {
  "DefaultConnection": "Server=.;Database=EFCoreDemo;Trusted_Connection=True;"
}
Here we are defining a connection string that will help us connect to our database locally or remotely.

Step 5: Add and Apply Migrations.
dotnet ef migrations add InitialCreate
dotnet ef database update

EF Core will:
  • Create a Migrations folder
  • Generate SQL commands
  • Apply them to your database
Step 6. Use the DbContext to Perform CRUD
public class ProductService
{
    private readonly AppDbContext _context;
    
    public ProductService(AppDbContext context)
    {
        _context = context;
    }

    public async Task AddProduct()
    {
        var product = new Product { Name = "Laptop", Price = 1500 };
        _context.Products.Add(product);
        await _context.SaveChangesAsync();
    }
}

EF Core will keep your code and database in sync using migrations, making your development fast, clean, and flexible.

What is the Database-First Approach?

In the Database-First approach, you start with an existing database, and Entity Framework Core generates the C# classes (models and DbContext) based on that database schema.

When to Use It?

  • You already have a pre-existing database
  • You're working with legacy systems
  • You want your C# models to match a database that someone else designed

Step-by-Step Example of Database-First Approach:

Step 1: Install Required NuGet Packages.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 2: Run the Scaffold Command
Use the following CLI command to reverse engineer your DB:
dotnet ef dbcontext scaffold "Your_Connection_String" Microsoft.EntityFrameworkCore.SqlServer -o Models

Explanation:
  • "Your_Connection_String" – The connection string to your existing DB
  • Microsoft.EntityFrameworkCore.SqlServer – The database provider
  • -o Models – Output directory for generated models and DbContext
What It Generates:
  • DbContext file → manages the connection to the DB
  • Model classes for each table → mapped to DB tables

What is the Repository Pattern?

The Repository Pattern acts as a mediator between the business logic and the data access layer. It hides the details of data access and provides a simple and consistent API for performing database operations.

Benefits:
  • Encapsulates data access logic
  • Promotes loose coupling
  • Makes unit testing easier
  • Clean separation of concerns

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS