Getting Started with Entity Framework Core

Note: This guide assumes you have a basic understanding of C# and .NET development.

What is Entity Framework Core?

Entity Framework Core (EF Core) is a modern, cross-platform, open-source, and extensible version of the popular Entity Framework data access technology for .NET. EF Core is an Object-Relational Mapper (ORM) that enables .NET developers to work with a database using .NET objects that map to the database schema. This means you can interact with your data using strongly-typed objects, rather than writing raw SQL queries.

Prerequisites

Installation

To use EF Core, you need to install the necessary NuGet packages. The core package is Microsoft.EntityFrameworkCore. You'll also need a provider package for your specific database. For example, to use SQL Server, you'd install:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

If you plan to use EF Core tools for command-line operations (like migrations), you'll also need:

dotnet add package Microsoft.EntityFrameworkCore.Tools

Defining Your Model

Your model is composed of classes that represent the tables in your database. These are often referred to as Plain Old CLR Objects (POCOs).


public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public virtual ICollection<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; }
}
            

Defining Your DbContext

The DbContext class is the primary class for interacting with the database. It represents a session with the database and allows you to query and save data. You create a class that derives from DbContext and includes DbSet<TEntity> properties for each entity in your 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)
    {
        // Replace with your actual connection string
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;");
    }
}
            

Creating the Database (Migrations)

EF Core Migrations is a powerful feature that allows you to evolve your database schema over time as your application's model changes. To create the initial database, you'll use the EF Core tools.

  1. Open your project's directory in a terminal.
  2. Run the following command to add an initial migration:
    dotnet ef migrations add InitialCreate
  3. Apply the migration to create the database:
    dotnet ef database update
Tip: Ensure you have the Microsoft.EntityFrameworkCore.Tools NuGet package installed and that your project is set as the startup project in your IDE or configured correctly in the terminal.

Performing Database Operations

Now you can use your DbContext to interact with the database.

Adding Data


using (var context = new BloggingContext())
{
    var blog = new Blog { Url = "http://sample.com/blogs/one" };
    context.Blogs.Add(blog);
    context.SaveChanges(); // Persists changes to the database
}
            

Querying Data


using (var context = new BloggingContext())
{
    var blogs = context.Blogs
                       .Where(b => b.Url.Contains("sample.com"))
                       .OrderBy(b => b.Url)
                       .ToList(); // Executes the query against the database

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

Updating Data


using (var context = new BloggingContext())
{
    var blogToUpdate = context.Blogs.FirstOrDefault(b => b.Url == "http://sample.com/blogs/one");
    if (blogToUpdate != null)
    {
        blogToUpdate.Url = "http://updated.com/blogs/one";
        context.SaveChanges();
    }
}
            

Deleting Data


using (var context = new BloggingContext())
{
    var blogToDelete = context.Blogs.FirstOrDefault(b => b.Url == "http://sample.com/blogs/one");
    if (blogToDelete != null)
    {
        context.Blogs.Remove(blogToDelete);
        context.SaveChanges();
    }
}
            

Next Steps

This guide provides a basic introduction to Entity Framework Core. To learn more, explore the following topics: