MSDN

Microsoft Developer Network

Entity Framework Core Documentation

Welcome to the official documentation for Entity Framework Core (EF Core). EF Core is a modern, cross-platform, open-source, extensible object-relational mapper (ORM) for .NET.

Introduction

Entity Framework Core simplifies data access in .NET applications by allowing developers to work with a conceptual model instead of directly writing database queries. It translates your object-oriented code into SQL statements that can be executed against a variety of database providers.

Getting Started

This section guides you through the initial steps of using EF Core in your projects.

Installation

To use EF Core, you need to install the appropriate NuGet packages for your project and the database provider you intend to use. For example, to use SQL Server:


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

Creating a Model

EF Core uses Plain Old CLR Objects (POCOs) to represent your data. You define your entities as classes:


public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public List<Post> Posts { get; set; }
}

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; }
}
            

Setting up DbContext

The DbContext is your primary class for interacting with the database. It represents a session with the database and allows you to query and save data.


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=Blogging;Trusted_Connection=True;");
    }
}
            

Migrations

Migrations allow you to evolve your database schema over time as your application model changes. They are an integral part of EF Core's development workflow.

To enable migrations, first ensure you have installed Microsoft.EntityFrameworkCore.Tools. Then, use the Package Manager Console or the .NET CLI:


# Add an initial migration
dotnet ef migrations add InitialCreate

# Apply migrations to the database
dotnet ef database update
            

Core Concepts

Understand the fundamental building blocks of EF Core.

Querying Data

You can query data using LINQ to Entities. EF Core translates your LINQ queries into SQL.


using var db = new BloggingContext();
var blogs = db.Blogs
              .Where(b => b.Url.Contains("example.com"))
              .OrderBy(b => b.Url);

foreach (var blog in blogs)
{
    Console.WriteLine($"Blog URL: {blog.Url}");
}
            

Saving Data

Add, update, and delete entities by modifying your DbContext and calling SaveChanges().


using var db = new BloggingContext();

// Add a new blog
var newBlog = new Blog { Url = "http://new.example.com" };
db.Blogs.Add(newBlog);
db.SaveChanges();

// Update a blog
var existingBlog = db.Blogs.Find(1);
if (existingBlog != null)
{
    existingBlog.Url = "http://updated.example.com";
    db.SaveChanges();
}

// Delete a blog
var blogToDelete = db.Blogs.Find(2);
if (blogToDelete != null)
{
    db.Blogs.Remove(blogToDelete);
    db.SaveChanges();
}
            

Relationships

EF Core supports defining relationships between entities, such as one-to-many, many-to-many, and one-to-one.

Refer to the Relationships Modeling documentation for detailed configuration.

Concurrency Control

EF Core provides mechanisms to handle concurrent updates to the same data.

Learn more about Concurrency Control.

Transactions

EF Core supports database transactions to ensure atomicity of operations.


using var db = new BloggingContext();
using var transaction = db.Database.BeginTransaction();

try
{
    db.Blogs.Add(new Blog { Url = "http://temp.example.com" });
    db.SaveChanges();
    // Perform other operations
    transaction.Commit();
}
catch (Exception)
{
    transaction.Rollback();
    throw;
}
            

Advanced Topics

Explore more advanced features and techniques for optimizing and customizing EF Core.

Performance Tuning

Optimize query performance using techniques like projection, compiled queries, and efficient data loading strategies.

See Performance Tuning.

Raw SQL Queries

Execute raw SQL queries when LINQ is not sufficient or for performance optimizations.


var blogs = db.Blogs.FromSqlRaw("SELECT * FROM Blogs WHERE Url LIKE '%example.com'");
            

Stored Procedures

EF Core allows you to call stored procedures and map their results to your entities.

Explore Calling Stored Procedures.

Change Tracking

Understand how EF Core tracks changes to entities and manages their state.

Details on Change Tracking.

Lazy Loading

Enable lazy loading to automatically load related entities when they are first accessed.

Configure Lazy Loading.

Eager Loading

Use eager loading with Include() to load related entities as part of the initial query.


var blogsWithPosts = db.Blogs
                       .Include(b => b.Posts)
                       .ToList();
            

API Reference

For detailed information on EF Core classes, methods, and properties, please refer to the official EF Core API Reference on Microsoft Learn.