Entity Framework Core: Getting Started

This guide will walk you through the essential steps to start using Entity Framework Core (EF Core) in your .NET applications. EF Core is a modern object-relational mapper (ORM) that enables .NET developers to work with a database using .NET objects that makes them effectively use the language of a database.

What is Entity Framework Core?

EF Core provides a set of Data Access technologies that enable .NET object to be worked with storage models such as relational databases. It allows you to:

Prerequisites

Before you begin, ensure you have the following installed:

Installation

To use EF Core, you need to install the appropriate NuGet packages. For example, to work with SQL Server, you would install:

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

The Microsoft.EntityFrameworkCore.Tools package is essential for database migrations.

Steps to Get Started

1. Define Your Model

Start by defining your domain model classes. These are plain C# objects (POCOs) that represent your database tables.

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

2. Create a DbContext

A DbContext instance represents a session with the database and allows you to query and save data. It's the primary way to interact with EF Core.

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)
    {
        // Replace with your actual connection string
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;");
    }
}

3. Database Migrations

EF Core Migrations allow you to incrementally evolve your database schema as your application's model changes. Use the .NET CLI to create and apply migrations.

First, enable migrations in your project:

dotnet ef migrations add InitialCreate

This command creates a migration file. Then, apply the migration to your database:

dotnet ef database update

4. Querying Data

You can query data using LINQ against your DbSet properties.

using (var context = new BloggingContext())
{
    var blogs = context.Blogs.ToList();
    foreach (var blog in blogs)
    {
        Console.WriteLine($"Blog URL: {blog.Url}");
    }
}

5. Saving Data

To add, modify, or remove data, you interact with your DbContext.

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

    // Update a blog
    var blogToUpdate = context.Blogs.FirstOrDefault(b => b.Url == "http://example.com");
    if (blogToUpdate != null)
    {
        blogToUpdate.Url = "http://updatedexample.com";
        context.SaveChanges();
    }

    // Delete a blog
    var blogToDelete = context.Blogs.FirstOrDefault(b => b.Url == "http://updatedexample.com");
    if (blogToDelete != null)
    {
        context.Blogs.Remove(blogToDelete);
        context.SaveChanges();
    }
}
Note: For advanced configurations, including dependency injection, refer to the official EF Core documentation.

Next Steps

Congratulations! You've successfully set up and used EF Core. To deepen your understanding, explore these topics: