Documentation

Getting Started with Entity Framework Core

Welcome to the getting started guide for Entity Framework Core (EF Core)! EF Core is a lightweight, extensible, and cross-platform data access technology for .NET applications. This guide will walk you through the fundamental steps to start using EF Core in your projects.

Prerequisites

Before you begin, ensure you have the following installed:

Installation

The first step is to install the necessary EF Core NuGet packages. You can do this using the .NET CLI or the NuGet Package Manager in your IDE. For this guide, we'll focus on the .NET CLI.

For Console Applications or Class Libraries

Navigate to your project directory in the terminal and run the following commands:

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

Microsoft.EntityFrameworkCore.SqlServer is the EF Core provider for SQL Server. You can replace SqlServer with other providers like Npgsql for PostgreSQL, MySql.Data.EntityFrameworkCore for MySQL, or Microsoft.EntityFrameworkCore.Sqlite for SQLite.

Microsoft.EntityFrameworkCore.Tools provides command-line tools for scaffolding, migrations, and other EF Core operations.

Defining Your Model

EF Core uses your .NET classes to represent your database tables. These classes are often referred to as "entities." Let's define a simple Blog entity:

Create a file named Blog.cs with the following content:

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

And a corresponding Post entity:

Create a file named Post.cs with the following content:

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

Creating Your DbContext

The DbContext class is the primary way to interact with your database. It represents a session with the database and allows you to query and save data. Your derived context is typically included in your model classes or in a separate folder.

Create a file named BloggingContext.cs with the following content:

using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    {
    }

    // Optional: Configure conventions, relationships, etc.
    // protected override void OnModelCreating(ModelBuilder modelBuilder)
    // {
    //     // Example: Configure primary key name
    //     modelBuilder.Entity<Blog>()
    //         .HasKey(b => b.BlogId);
    // }
}

In this context, DbSet<TEntity> properties represent collections of entities that can be queried from the database.

Configuring the Database Connection

You need to tell EF Core which database to connect to. This is typically done in your application's startup code or configuration file.

Using appsettings.json (for ASP.NET Core)

Add a connection string to your appsettings.json file:

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;"
  }
}

And configure your DbContext in Startup.cs (or Program.cs for .NET 6+):

// For .NET 6+ Program.cs
builder.Services.AddDbContext<BloggingContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("BloggingDatabase")));

Using Options in Main method (for Console Apps)

using System;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;");
        
        using (var context = new BloggingContext(optionsBuilder.Options))
        {
            // Your application logic here
        }
    }
}

Scaffolding a Database from Existing Code

If you already have a database and want EF Core to generate the C# model classes, you can use scaffolding. First, ensure your DbContext is set up and you have the necessary tools installed.

Run the following command in your project directory:

dotnet ef dbcontext scaffold "Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

This command will generate a DbContext and entity classes in a folder named Models based on your existing database.

Creating the Database from Your Model

If you're starting with an empty database or want to evolve your schema, EF Core Migrations are the way to go. They allow you to incrementally update your database schema as your application's model changes.

  1. Enable Migrations:
    dotnet ef migrations add InitialCreate
    This command generates a migration file that EF Core uses to create your database schema.
  2. Apply Migrations:
    dotnet ef database update
    This command applies the pending migrations to your database, creating the necessary tables and columns.
Note: Ensure you have run dotnet restore after adding the NuGet packages.

Performing Basic Operations

Now that you have your context set up, you can start interacting with your database.

Adding Data

using (var context = new BloggingContext(optionsBuilder.Options))
{
    var blog = new Blog { Url = "http://blogs.msdn.microsoft.com/dotnet" };
    context.Blogs.Add(blog);
    context.SaveChanges(); // Persist changes to the database
}

Querying Data

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

    var firstBlog = context.Blogs.FirstOrDefault();
    if (firstBlog != null)
    {
        Console.WriteLine($"First Blog ID: {firstBlog.BlogId}");
    }
}

Updating Data

using (var context = new BloggingContext(optionsBuilder.Options))
{
    var blogToUpdate = context.Blogs.FirstOrDefault(b => b.Url.Contains("msdn"));
    if (blogToUpdate != null)
    {
        blogToUpdate.Url = "https://devblogs.microsoft.com/dotnet/";
        context.SaveChanges();
    }
}

Deleting Data

using (var context = new BloggingContext(optionsBuilder.Options))
{
    var blogToDelete = context.Blogs.FirstOrDefault(b => b.Url.StartsWith("http://old-domain"));
    if (blogToDelete != null)
    {
        context.Blogs.Remove(blogToDelete);
        context.SaveChanges();
    }
}

Conclusion

This guide covered the essential steps to get started with Entity Framework Core: installation, defining models, setting up the DbContext, configuring the connection, and performing basic data operations. EF Core offers much more, including advanced querying, change tracking, concurrency control, and much more. Explore the rest of the MSDN .NET documentation to deepen your understanding.