Entity Framework Core - Introduction

Your guide to modern data access with .NET

What is Entity Framework Core?

Entity Framework Core (EF Core) is a modern, lightweight, extensible data access platform for .NET. It is a rewrite of the popular Entity Framework from the ground up.

EF Core allows developers to interact with databases using .NET objects, eliminating the need to write most of the data-access code. It supports a wide range of database providers, including SQL Server, SQLite, PostgreSQL, MySQL, and more.

Key Concepts

  • DbContex: The primary class used to interface with the database. It represents a session with the database and can be used to query and save data.
  • DbSet<TEntity>: Represents a collection of all entities in the store for a given type. You can add, delete, and modify entities by interacting with instances of DbSet<TEntity>.
  • Entity: A .NET class that maps to a table in the database.
  • Model: Represents the schema of the data being accessed.

Why Use Entity Framework Core?

  • Productivity: Reduces the amount of boilerplate data access code you need to write.
  • Type Safety: Allows you to work with your data using strongly-typed .NET objects.
  • Database Agnosticism: You can switch database providers with minimal code changes.
  • Modern Features: Supports the latest .NET features and performance optimizations.

Getting Started

To start using EF Core, you typically need to:

  1. Install the necessary NuGet packages.
  2. Define your entity classes.
  3. Create a DbContext derived class.
  4. Configure your DbContext with database provider and connection string.
  5. Use your DbContext to query and save data.

Here's a simple example of defining an entity and a DbContext:


using Microsoft.EntityFrameworkCore;

// Define an entity
public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Define the DbContext
public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Optional: Configure your model here
        modelBuilder.Entity<Product>().HasKey(p => p.ProductId);
        modelBuilder.Entity<Product>().Property(p => p.Name).IsRequired().HasMaxLength(100);
        modelBuilder.Entity<Product>().Property(p => p.Price).HasColumnType("decimal(18, 2)");
    }
}
                

Further Reading

This page provides a high-level overview. For detailed information and step-by-step guides, please explore the following sections: