Entity Framework Core In-Depth

Introduction to Entity Framework Core

Entity Framework Core (EF Core) is a modern, open-source, cross-platform version of the familiar Entity Framework data access technology. It's a lightweight, extensible, and high-performance Object-Relational Mapper (ORM) for .NET that enables developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers traditionally need to write.

EF Core maps your .NET objects to your database schema. This abstraction allows you to interact with your data using strongly-typed objects and LINQ queries, making your code more readable, maintainable, and less prone to errors. It supports a wide range of database providers, including SQL Server, PostgreSQL, MySQL, SQLite, Oracle, and more.

Core Concepts

Understanding the fundamental building blocks of EF Core is crucial for effective use. These include:

Getting Started with EF Core

This section guides you through the initial steps of setting up EF Core in your .NET application. You'll learn how to:

Tip: The Code-First approach is generally recommended for new projects as it allows you to define your domain model first and let EF Core manage the database schema.

Modeling Your Data

EF Core provides flexible ways to define your data model:

1. Conventions

EF Core uses a set of default conventions to infer your model. For example, a public property of a type is mapped to a column, and a DbSet<TEntity> property on your DbContext is mapped to a table.

2. Data Annotations

You can use data annotations in your entity classes to configure aspects of your model, such as primary keys, foreign keys, and column properties.

public class Blog
{
    public int Id { get; set; } // Conventionally the primary key
    [Required] // Data annotation for NOT NULL
    [MaxLength(200)] // Data annotation for string length
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
}

3. Fluent API

For more complex configurations or when data annotations are not sufficient, you can use the Fluent API by overriding the OnModelCreating method in your DbContext.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .HasIndex(b => b.Url)
        .IsUnique();
}

Querying Data with LINQ

EF Core leverages Language Integrated Query (LINQ) to allow you to query your data in a strongly-typed and expressive way. You can filter, sort, group, and project your data directly in C# code.

// Get all blogs from a specific URL
var blogs = context.Blogs
                 .Where(b => b.Url.Contains("example.com"))
                 .OrderBy(b => b.Url)
                 .ToList();

// Include related data (e.g., posts for each blog)
var blogsWithPosts = context.Blogs
                         .Include(b => b.Posts)
                         .ToList();

Saving Data (Create, Update, Delete)

EF Core simplifies the process of persisting changes to your database.

Adding New Entities

var newBlog = new Blog { Url = "http://newblog.com" };
context.Blogs.Add(newBlog);
await context.SaveChangesAsync();

Updating Existing Entities

EF Core tracks changes automatically for entities retrieved through the context. For detached entities, you can use Update or mark entities as modified.

var existingBlog = await context.Blogs.FindAsync(1);
if (existingBlog != null)
{
    existingBlog.Url = "http://updatedblog.com";
    await context.SaveChangesAsync();
}

Deleting Entities

var blogToDelete = await context.Blogs.FindAsync(2);
if (blogToDelete != null)
{
    context.Blogs.Remove(blogToDelete);
    await context.SaveChangesAsync();
}

Database Migrations

EF Core Migrations provide a way to incrementally update your database schema to match your evolving data model without losing existing data.

Note: Migrations are a powerful tool for managing database schema changes in a controlled and versioned manner.

Advanced Topics

EF Core offers a rich set of features for more complex scenarios:

This in-depth documentation aims to provide a comprehensive understanding of EF Core, empowering you to build robust and efficient data-driven applications.