Getting Started with Entity Framework Core

Entity Framework Core (EF Core) is a modern, cross-platform, open-source version of the popular Entity Framework data access technology. It provides a familiar abstraction layer over your database, allowing you to work with data using .NET objects.

What is Entity Framework Core?

EF Core enables you to:

Prerequisites

Before you begin, ensure you have the following installed:

Installation

You can install EF Core using the .NET CLI. For example, to add the SQL Server provider to your project:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

You'll also typically need the design-time tools for migrations:

dotnet add package Microsoft.EntityFrameworkCore.Design

Your First EF Core Application

1. Define Your Model

Create Plain Old CLR Objects (POCOs) that represent your database tables.

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

2. Create Your DbContext

The DbContext class is the main entry point for interacting with your database.

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;"); } }
It's recommended to configure the DbContext using dependency injection in ASP.NET Core applications rather than overriding OnConfiguring.

3. Create the Database (Migrations)

EF Core Migrations allow you to incrementally update your database schema as your model changes.

First, create an initial migration:

dotnet ef migrations add InitialCreate

Then, apply the migration to create the database:

dotnet ef database update
Make sure to have the Microsoft.EntityFrameworkCore.Design package installed and the EF Core tools are available in your PATH.

4. Query and Save Data

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

using (var context = new BloggingContext()) { // Add a new blog var blog = new Blog { Url = "http://example.com", Title = "My First Blog" }; context.Blogs.Add(blog); context.SaveChanges(); // Query blogs var query = from b in context.Blogs orderby b.Url select b; foreach (var item in query) { Console.WriteLine($"Blog: {item.Title} ({item.Url})"); } // Add a post to an existing blog blog.Posts.Add(new Post { Title = "Hello World", Content = "This is my first post!" }); context.SaveChanges(); }

Key Concepts

Next Steps

Explore these advanced topics: