Entity Framework

 

Entity Framework (EF)

Entity Framework (EF) is a powerful, open-source Object-Relational Mapper (ORM) from Microsoft that enables .NET developers to work with a database using C# objects (domain-specific objects) instead of writing most of the traditional data-access code or raw SQL queries.

Key Concepts and Benefits

Abstraction: EF abstracts the underlying database tables and columns, allowing developers to focus on the business logic and entity relationships within their C# code.

LINQ Integration: It primarily uses Language-Integrated Query (LINQ) to query data using strongly typed C# syntax. EF Core translates these LINQ queries into database-specific SQL queries (e.g., for SQL Server, MySQL, PostgreSQL, SQLite).

Change Tracking: EF automatically tracks changes made to your C# objects and generates the appropriate INSERTUPDATE, and DELETE commands when you call the SaveChanges() method on the database context.

Migrations: EF provides a migrations feature that allows developers to evolve the database schema over time as their C# model changes, using commands like Add-Migration and Update-Database.

EF Core vs. EF 6

The modern, cross-platform version is Entity Framework Core (EF Core), which is recommended for all new applications. The older Entity Framework 6 (EF6) is the classic version and is still supported for security fixes but is no longer actively developed with new features.

Approaches to Data Modeling

EF primarily supports two main development approaches:

  • Code-First: This is the most common approach in modern .NET development.

    • You define your data models (C# classes) and the database context class in C# code.

    • EF Core then uses this code to generate the database and its schema (or update an existing one using migrations). This approach aligns well with Domain-Driven Design principles.

  • Database-First: In this approach, you start with an existing database.

  • You use EF Core tools (like the dotnet ef CLI or NuGet Package Manager Console commands) to reverse engineer the database schema and generate the corresponding C# entity and context classes automatically.

Basic Usage Example (Code-First)

Here is a simple example of how EF Core allows you to interact with a database using C# code:

1. Define a Model (C# class)

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } // EF Core knows this is non-nullable from context
    public decimal Price { get; set; }
}

2. Define a Database Context (inherits from DbContext)

using Microsoft.EntityFrameworkCore;

public class YouTubeDBContext : DbContext
{
    public YouTubeDBContext(DbContextOptions<YouTubeDBContext> options) : base(options) { }

    // DbSet represents the collection of all entities in the context
    public DbSet<Product> Products { get; set; }
}

3. Query Data using LINQ

using (var db = new YouTubeDBContext(options))
{
    // Example LINQ query to find a product
    var product = db.Products
                    .Where(p => p.Name == "Laptop")
                    .FirstOrDefault();

    if (product != null)
    {
        Console.WriteLine($"Found: {product.Name} at {product.Price:C}");
    }
}

This C# LINQ expression is translated into an efficient SQL query behind the scenes.

implement entity framework in web api

Implementing Entity Framework (EF) in a Web API involves several key steps, primarily using the Code First approach with modern ASP.NET Core for robust data access.

Here is a step-by-step guide:

Prerequisites

  • Visual Studio 2022 or newer.
  • .NET SDK (e.g., .NET 8 or 9).
  • A database server (e.g., SQL Server, SQLite, PostgreSQL).

Steps

  • 1. Create a New ASP.NET Core Web API Project

    • Open Visual Studio and select Create a new project.
    • Choose the ASP.NET Core Web API template and follow the prompts.
  • 2. Install Entity Framework Core NuGet Packages Use the NuGet Package Manager Console in Visual Studio to install the necessary packages for your chosen database provider:

# For SQL Server
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
# Microsoft.EntityFrameworkCore.Tools (for migrations)
# To use EF Core tools for migrations (install globally if not already)

dotnet tool install --global dotnet-ef
  • 3. Define Your Data Model (Entity Class) Create a Models folder and add a C# class representing your database table (e.g., Employee.cs).
// Models/Employee.cs
using System.ComponentModel.DataAnnotations;

namespace WebApiCoreWithEF.Models
{
    public class Employee
    {
        [Key]
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Gender { get; set; }
        // ... other properties
    }
}
  • 4. Create a Database Context Create a Context folder and add a class that inherits from DbContext and exposes DbSet properties for your entities. This class coordinates EF functionality for the model.
// Context/CompanyContext.cs
using Microsoft.EntityFrameworkCore;
using WebApiCoreWithEF.Models;

namespace WebApiCoreWithEF.Context
{
    public class CompanyContext : DbContext
    {
        public CompanyContext(DbContextOptions<CompanyContext> options) : base(options) { }

        public DbSet<Employee> Employees { get; set; }
    }
}

  • 5. Configure the Connection String

Add your database connection string to the appsettings.json file.

// appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=CompanyDB;Integrated Security=True;TrustServerCertificate=True;"
  }
}
  • 6. Register the DbContext with Dependency Injection In modern ASP.NET Core (.NET 6+), register your context in the Program.cs file using the built-in dependency injection container.
// Program.cs
// ... other code ...

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<CompanyContext>(options =>
    options.UseSqlServer(connectionString));

// ... other code ...
  • 7. Create the Database using Migrations Use the Package Manager Console or terminal to create a migration and update your database schema based on your models.
dotnet ef migrations add InitialCreate
dotnet ef database update
  • 8. Add a Web API Controller Right-click the Controllers folder and select Add > Controller. Choose the API Controller with actions, using Entity Framework option and select your Model and Data context classes to automatically generate basic CRUD action methods. The generated controller will inject the CompanyContext via its constructor and use it to perform data operations asynchronously.
// Controllers/EmployeesController.cs (Generated Code Snippet)
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
    private readonly CompanyContext _context;

    public EmployeesController(CompanyContext context)
    {
        _context = context;
    }

    // GET: api/Employees
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees()
    {
        return await _context.Employees.ToListAsync();
    }
    
    // ... Post, Put, Delete methods are also generated ...
}

Your Web API is now integrated with Entity Framework and ready to perform data operations. You can test the endpoints using tools like Postman or Swagger UI.

Comments

Popular posts from this blog