Entity Framework Core Overview

Entity Framework Core (EF Core) is a modern, cross-platform, extensible data access framework for .NET. It is a lightweight, high-performance, and open-source version of the popular Entity Framework. EF Core allows developers to work with a database using .NET objects, abstracting away much of the low-level data access code.

Key Features of EF Core

Core Concepts

DbContext

The DbContext is the primary class that represents a session with the database and allows you to query and save data. It's your entry point to the EF Core world.


using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionString");
    }
}
            

DbSet<TEntity>

A DbSet<TEntity> represents a collection of a given entity type in the context, which can be used to query and save data for that entity.

Entities

Plain Old CLR Objects (POCOs) that represent tables in your database. EF Core maps these objects to your database schema.

Data Access

EF Core provides several ways to interact with your data:

Migrations

EF Core Migrations is a powerful feature that allows you to evolve your database schema in step with your object model. You can create new migrations manually or have EF Core generate them automatically based on changes to your DbContext and entity models.

Common commands:

Important: Always back up your database before applying migrations in a production environment.

Scenarios

Code-First

In the Code-First approach, you define your entity classes and DbContext first, and then EF Core generates the database schema based on your code.

Database-First

In the Database-First approach, you can scaffold EF Core model classes from an existing database. This is useful when you have a legacy database.

Tip: For new projects, the Code-First approach is generally recommended for its flexibility and ease of development.

Next Steps

To get started with EF Core, explore the following topics: