.NET Documentation - Microsoft
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.
Before performing any operations, ensure you have your DbContext
and entity models configured. This example assumes a simple `Blog` entity and a `BloggingContext`.
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; }
}
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
}
}
To add a new entity, instantiate it, add it to the appropriate DbSet
, and then call SaveChanges
.
using var context = new BloggingContext(options);
var newBlog = new Blog { Url = "http://example.com/blog" };
context.Blogs.Add(newBlog);
context.SaveChanges();
EF Core uses LINQ for querying data. You can retrieve all records, specific records by ID, or filter based on various criteria.
using var context = new BloggingContext(options);
var allBlogs = context.Blogs.ToList();
// Process allBlogs
using var context = new BloggingContext(options);
var blogIdToFind = 1;
var specificBlog = context.Blogs.Find(blogIdToFind);
if (specificBlog != null)
{
// Process specificBlog
}
using var context = new BloggingContext(options);
var blogsWithPosts = context.Blogs
.Where(b => b.Posts.Any())
.ToList();
// Process blogsWithPosts
To update a record, retrieve it, modify its properties, and then call SaveChanges
. EF Core tracks changes automatically.
using var context = new BloggingContext(options);
var blogToUpdate = context.Blogs.Find(1);
if (blogToUpdate != null)
{
blogToUpdate.Url = "http://updated-example.com/blog";
context.SaveChanges();
}
To delete a record, retrieve it, mark it for removal using Remove
, and then call SaveChanges
.
using var context = new BloggingContext(options);
var blogToDelete = context.Blogs.Find(2);
if (blogToDelete != null)
{
context.Blogs.Remove(blogToDelete);
context.SaveChanges();
}
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.