Entity Framework Core

Entity Framework Core (EF Core) is a modern, cross-platform, extensible data access framework for .NET. It has been rewritten from the ground up and is a lightweight and extensible version of the popular Entity Framework. EF Core can be used with many different databases, including Microsoft SQL Server, SQLite, MySQL, PostgreSQL, Oracle, and more.

Key Features:

What is EF Core?

EF Core acts as an Object-Relational Mapper (ORM). It enables developers to work with a database using .NET objects instead of SQL queries. This simplifies data access and makes applications more maintainable. EF Core maps your domain classes (POCOs - Plain Old CLR Objects) to database tables, allowing you to query and save data using familiar C# or F# syntax.

Core Concepts

DbContext

The DbContext is the primary class used to interact with the database. It represents a session with the database and is a gateway to querying and saving data. You typically create a class that inherits from DbContext and defines DbSet<TEntity> properties for each entity in your domain model.


using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public ICollection<Post> Posts { get; } = new List<Post>();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}
        

DbSet<TEntity>

A DbSet<TEntity> represents a collection of all entities in the store for a given type. This collection is accessible from a DbContext instance.

Entities

Entities are POCO classes that represent the data you store in the database. EF Core can infer much of the mapping information from conventions, but you can also configure it explicitly using Data Annotations or the Fluent API.

Getting Started

To start using EF Core, you need to install the appropriate NuGet packages. The core package is Microsoft.EntityFrameworkCore, and you'll need a database provider package for your chosen database (e.g., Microsoft.EntityFrameworkCore.SqlServer).

For a quick start, refer to the Getting Started section.