Skip to content

Instantly share code, notes, and snippets.

@emonarafat
Created June 29, 2025 16:49
Show Gist options
  • Select an option

  • Save emonarafat/8bbc4791ed533d705e3d0a12915876eb to your computer and use it in GitHub Desktop.

Select an option

Save emonarafat/8bbc4791ed533d705e3d0a12915876eb to your computer and use it in GitHub Desktop.
“EF Core Tracks Everything” — and 5 Other Lies Slowing Down Your App
// EFCoreMythSamples.cs
// Demonstrates tracked vs untracked queries and minimal EF Core usage
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet<Post> Posts => Set<Post>();
public DbSet<Comment> Comments => Set<Comment>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=BlogDb;");
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public List<Comment> Comments { get; set; } = new();
}
public class Comment
{
public int Id { get; set; }
public string Text { get; set; } = string.Empty;
public int PostId { get; set; }
}
public class SampleQueries
{
public async Task<List<PostDto>> GetRecentPostsAsync(BloggingContext db)
{
// ✅ Read-only projection with AsNoTracking (Myth #1)
return await db.Posts
.AsNoTracking()
.OrderByDescending(p => p.Id)
.Select(p => new PostDto
{
Id = p.Id,
Title = p.Title,
CommentCount = p.Comments.Count
})
.ToListAsync();
}
public async Task AddCommentAsync(BloggingContext db, int postId, string text)
{
var comment = new Comment { PostId = postId, Text = text };
db.Comments.Add(comment);
await db.SaveChangesAsync();
}
}
public record PostDto(int Id, string Title, int CommentCount);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment