Created
June 29, 2025 16:49
-
-
Save emonarafat/8bbc4791ed533d705e3d0a12915876eb to your computer and use it in GitHub Desktop.
“EF Core Tracks Everything” — and 5 Other Lies Slowing Down Your App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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