Entity Framework Core: Getting Started

Updated: October 26, 2023

Welcome to the getting started guide for Entity Framework Core (EF Core)! This guide will walk you through the essential steps to begin using EF Core to interact with your database in .NET applications.

What is Entity Framework Core?

Entity Framework Core is a modern, cross-platform, open-source, and extensible Object-Relational Mapper (ORM) for .NET. It enables developers to work with databases using .NET objects, eliminating the need for most of the data-access code they typically need to write.

Prerequisites

Step 1: Create a .NET Project

First, create a new .NET project. For this example, we'll create a Console Application:

dotnet new console -o MyEFCoreApp cd MyEFCoreApp

Step 2: Install EF Core NuGet Packages

You'll need to install the core EF Core package and the package for your specific database provider. For this guide, we'll use SQL Server. If you're using a different database (like SQLite, PostgreSQL, MySQL), refer to the EF Core Providers documentation.

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

Microsoft.EntityFrameworkCore.Tools is essential for using EF Core Migrations from the command line.

Step 3: Define Your Model Classes

Create Plain Old CLR Objects (POCOs) that represent the entities in your application. These classes will map to database tables.

// Models/Blog.cs public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } // Models/Post.cs 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; } }

EF Core uses naming conventions to infer relationships and primary keys. For example, `BlogId` is recognized as the primary key for the `Blog` class, and the `Blog Blog` property establishes a navigation property to the related `Blog` entity.

Step 4: Create Your DbContext

The DbContext class represents a session with the database and allows you to query and save data. It's the central class of EF Core.

// Data/ApplicationDbContext.cs using Microsoft.EntityFrameworkCore; using MyEFCoreApp.Models; namespace MyEFCoreApp.Data { public class ApplicationDbContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Optional: Configure model relationships, keys, etc. here base.OnModelCreating(modelBuilder); } } }

Step 5: Configure the DbContext

You need to tell EF Core how to connect to your database. This is typically done in the `Program.cs` file for .NET 6+ or `Startup.cs` for older versions.

// Program.cs (for .NET 6 and later) using Microsoft.EntityFrameworkCore; using MyEFCoreApp.Data; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); // Or AddControllers, AddMvc depending on your app type var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); var app = builder.Build(); // ... rest of your Program.cs configuration ... app.Run();

You'll also need to add a connection string to your `appsettings.json` file:

{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyEFCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }

Note: Replace the connection string with your actual database details. For development, using `(localdb)\mssqllocaldb` is common for SQL Server Express LocalDB.

Step 6: Create a Database Migration

Migrations allow you to incrementally update your database schema as your model changes. First, enable package management console or use the .NET CLI.

Using .NET CLI:

Ensure you are in your project directory.

dotnet ef migrations add InitialCreate dotnet ef database update

The `InitialCreate` migration will generate code to create your database tables based on your `DbContext` and model classes. `database update` applies this migration to your database.

Step 7: Querying Data

Now you can use your `DbContext` to query data.

// In your application logic (e.g., a controller or service) using (var context = new ApplicationDbContext(options)) // Assume options are provided { var blogs = context.Blogs.ToList(); foreach (var blog in blogs) { Console.WriteLine($"- {blog.Url}"); } var firstPost = context.Posts .Where(p => p.Title.Contains("EF Core")) .FirstOrDefault(); if (firstPost != null) { Console.WriteLine($"Found post: {firstPost.Title}"); } }

Step 8: Saving Data

You can add, modify, and delete entities.

// In your application logic using (var context = new ApplicationDbContext(options)) { // Add a new blog var newBlog = new Blog { Url = "https://example.com/newblog" }; context.Blogs.Add(newBlog); context.SaveChanges(); // Persist changes to the database // Add a new post to an existing blog var blogToUpdate = context.Blogs.Find(1); // Assuming blog with ID 1 exists if (blogToUpdate != null) { var newPost = new Post { Title = "My First EF Core Post", Content = "This is the content.", Blog = blogToUpdate // Associate with the blog }; context.Posts.Add(newPost); context.SaveChanges(); } // Update a post var postToUpdate = context.Posts.Find(1); // Assuming post with ID 1 exists if (postToUpdate != null) { postToUpdate.Content = "Updated content for the post."; context.SaveChanges(); } // Delete a post var postToDelete = context.Posts.Find(2); // Assuming post with ID 2 exists if (postToDelete != null) { context.Posts.Remove(postToDelete); context.SaveChanges(); } }

Tip: `DbContext.SaveChanges()` persists all pending changes for tracked entities. You can also use `DbContext.Add()`, `DbContext.Update()`, and `DbContext.Remove()` to change the state of entities.

Next Steps

This guide covers the very basics. To dive deeper, explore the following topics:

Happy coding with Entity Framework Core!