MSDN Documentation

Your comprehensive guide to Microsoft technologies.

Entity Framework Core

Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET. It allows developers to work with a database using .NET objects, eliminating the need for most of the data-access code they typically need to write.

Introduction to Entity Framework Core

EF Core is an evolution of the popular Entity Framework. It's lightweight, extensible, and has excellent performance. It enables you to:

Getting Started with EF Core

To get started with EF Core, you'll typically need to:

  1. Install the necessary NuGet packages. For example, for SQL Server:
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    dotnet add package Microsoft.EntityFrameworkCore.Tools
  2. Define your domain entities (POCO classes).
  3. Create a DbContext class that represents a session with the database and can be used to query and save data.
  4. Configure your model, either by convention or by using the Fluent API or Data Annotations.
  5. Set up your database connection string.

Example Entity:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public virtual 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 virtual Blog Blog { get; set; }
}

Example DbContext:

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Fluent API configuration can go here
        modelBuilder.Entity<Blog>().Property(b => b.Url).IsRequired().HasMaxLength(200);
    }
}

Core Concepts

Database Migrations

EF Core Migrations is a powerful feature that allows you to incrementally update your database schema to keep it in sync with your domain model. You can:

Tip: Ensure you have the EF Core tools installed globally or per project to use the dotnet ef commands.

Querying Data

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

using var context = new BloggingContext();

// Get all blogs
var blogs = context.Blogs.ToList();

// Find a specific blog by ID
var specificBlog = context.Blogs.Find(1);

// Query with filtering and ordering
var popularPosts = context.Posts
    .Where(p => p.Content.Length > 100)
    .OrderByDescending(p => p.PostId)
    .ToList();

// Include related data
var blogsWithPosts = context.Blogs.Include(b => b.Posts).ToList();

Saving Data

You can add, modify, and delete entities. Changes are tracked by the DbContext and then committed to the database.

using var context = new BloggingContext();

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

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

// Remove a post
var postToRemove = context.Posts.Find(5);
if (postToRemove != null)
{
    context.Posts.Remove(postToRemove);
    context.SaveChanges();
}

Advanced Topics

Note: EF Core supports various database providers, including SQL Server, SQLite, PostgreSQL, MySQL, Oracle, and more. You'll need to install the appropriate provider package.