MSDN Documentation

Getting Started with EF Core

Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET that supports advanced features and is designed to be extensible and performant. This guide will walk you through the basic steps to get started with EF Core in your .NET applications.

Prerequisites

Step 1: Create a New Project

Start by creating a new .NET project. For this example, we'll create a console application.

dotnet new console -o EFCoreGettingStarted
cd EFCoreGettingStarted

Step 2: Install EF Core Packages

You need to install the necessary EF Core NuGet packages. The most common ones are the core package and a database provider package. For this example, we'll use SQLite.

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

The Microsoft.EntityFrameworkCore.Design package is needed for tools like migrations.

Step 3: Define Your Model Classes

Define plain C# classes that represent the entities you want to store in your database. These are often referred to as POCOs (Plain Old CLR Objects).

Create a new file named Models.cs in your project and add the following:

namespace EFCoreGettingStarted
{
    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; }
    }
}

Step 4: Create a 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.

Create a new file named BloggingContext.cs and add the following:

using Microsoft.EntityFrameworkCore;

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

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // Configure the database provider and connection string
            optionsBuilder.UseSqlite("Data Source=blogging.db");
        }
    }
}

Step 5: Create the Database and Schema (Migrations)

EF Core uses migrations to incrementally update your database schema to match your model. You'll first need to enable the design-time components.

Install the EF Core tools:

dotnet tool install --global dotnet-ef
dotnet restore

Now, add your first migration:

dotnet ef migrations add InitialCreate

This will create a Migrations folder with code to create your database tables. You can inspect the generated files.

Apply the migration to create the database:

dotnet ef database update

This will create a blogging.db file in your project's output directory with the necessary tables.

Step 6: Interact with the Database

Now you can use your DbContext to add, query, and manipulate data.

Open your Program.cs file and replace its content with the following:

using System;
using System.Linq;

namespace EFCoreGettingStarted
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new BloggingContext())
            {
                // Create a new blog and add it to the database
                Console.WriteLine("Adding a new blog...");
                context.Blogs.Add(new Blog { Url = "http://sample.blogspot.com" });
                context.SaveChanges();

                // Query for all blogs
                Console.WriteLine("Querying for all blogs:");
                var blogs = context.Blogs
                    .OrderBy(b => b.Url)
                    .ToList();

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

                // Add a new post to an existing blog
                if (blogs.Any())
                {
                    var firstBlog = blogs.First();
                    Console.WriteLine($"\nAdding a new post to blog: {firstBlog.Url}");
                    firstBlog.Posts.Add(new Post { Title = "EF Core Basics", Content = "This is a first post about EF Core." });
                    context.SaveChanges();

                    // Query for posts in a blog
                    Console.WriteLine("Querying for posts in the blog:");
                    var posts = context.Posts
                        .Where(p => p.BlogId == firstBlog.BlogId)
                        .ToList();

                    foreach (var post in posts)
                    {
                        Console.WriteLine($"  - {post.Title}");
                    }
                }
            }

            Console.WriteLine("\nPress any key to exit.");
            Console.ReadKey();
        }
    }
}

Step 7: Run the Application

Execute the application to see the results.

dotnet run

Note: In a real-world application, you would typically configure your DbContext using dependency injection in an ASP.NET Core application, rather than hardcoding the connection string in OnConfiguring.

Next Steps

This guide covered the absolute basics. You can explore more advanced topics such as: