Entity Framework Core CRUD Samples

.NET Documentation - Microsoft

Performing CRUD Operations with EF Core

Entity Framework Core (EF Core) provides a robust and flexible way to interact with databases in .NET applications. This document covers common Create, Read, Update, and Delete (CRUD) operations using EF Core, along with practical code examples.

1. Setting up the Context and Model

Before performing any operations, ensure you have your DbContext and entity models configured. This example assumes a simple `Blog` entity and a `BloggingContext`.

Blog Entity


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

BloggingContext


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)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Fluent API configurations can go here
    }
}
                

2. Creating (Adding) New Records

To add a new entity, instantiate it, add it to the appropriate DbSet, and then call SaveChanges.

Adding a New Blog


using var context = new BloggingContext(options);

var newBlog = new Blog { Url = "http://example.com/blog" };
context.Blogs.Add(newBlog);
context.SaveChanges();
                

3. Reading (Querying) Records

EF Core uses LINQ for querying data. You can retrieve all records, specific records by ID, or filter based on various criteria.

Retrieving All Blogs


using var context = new BloggingContext(options);

var allBlogs = context.Blogs.ToList();
// Process allBlogs
                

Retrieving a Blog by ID


using var context = new BloggingContext(options);

var blogIdToFind = 1;
var specificBlog = context.Blogs.Find(blogIdToFind);

if (specificBlog != null)
{
    // Process specificBlog
}
                

Querying with Filtering


using var context = new BloggingContext(options);

var blogsWithPosts = context.Blogs
    .Where(b => b.Posts.Any())
    .ToList();
// Process blogsWithPosts
                

4. Updating Records

To update a record, retrieve it, modify its properties, and then call SaveChanges. EF Core tracks changes automatically.

Updating a Blog's URL


using var context = new BloggingContext(options);

var blogToUpdate = context.Blogs.Find(1);

if (blogToUpdate != null)
{
    blogToUpdate.Url = "http://updated-example.com/blog";
    context.SaveChanges();
}
                

5. Deleting Records

To delete a record, retrieve it, mark it for removal using Remove, and then call SaveChanges.

Deleting a Blog


using var context = new BloggingContext(options);

var blogToDelete = context.Blogs.Find(2);

if (blogToDelete != null)
{
    context.Blogs.Remove(blogToDelete);
    context.SaveChanges();
}
                

6. Batch Operations and Performance

For scenarios involving a large number of additions, updates, or deletions, consider using batching or bulk operations provided by libraries like Entity Framework Core Extensions for better performance.