dotnet --version
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
Create a DbContext with fluent configuration, migrations, query optimization with AsNoTracking, and split queries.
1 using Microsoft.EntityFrameworkCore; 2 using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 4 public class BlogDbContext : DbContext 5 { 6 public DbSet<Blog> Blogs => Set<Blog>(); 7 public DbSet<Post> Posts => Set<Post>(); 8 9 public BlogDbContext(DbContextOptions<BlogDbContext> options) : base(options) { } 10 11 protected override void OnModelCreating(ModelBuilder modelBuilder) 12 { 13 modelBuilder.ApplyConfiguration(new BlogConfiguration()); 14 modelBuilder.ApplyConfiguration(new PostConfiguration()); 15 } 16 } 17 18 public class Blog 19 { 20 public int Id { get; set; } 21 public string Title { get; set; } = default!; 22 public string Url { get; set; } = default!; 23 public List<Post> Posts { get; set; } = []; 24 } 25 26 public class Post 27 { 28 public int Id { get; set; } 29 public string Title { get; set; } = default!; 30 public string Content { get; set; } = default!; 31 public int BlogId { get; set; } 32 public Blog Blog { get; set; } = default!; 33 public DateTime PublishedAt { get; set; } 34 } 35 36 public class BlogConfiguration : IEntityTypeConfiguration<Blog> 37 { 38 public void Configure(EntityTypeBuilder<Blog> builder) 39 { 40 builder.HasKey(b => b.Id); 41 builder.Property(b => b.Title).IsRequired().HasMaxLength(200); 42 builder.Property(b => b.Url).IsRequired().HasMaxLength(500); 43 builder.HasIndex(b => b.Url).IsUnique(); 44 builder.HasMany(b => b.Posts) 45 .WithOne(p => p.Blog) 46 .HasForeignKey(p => p.BlogId) 47 .OnDelete(DeleteBehavior.Cascade); 48 } 49 } 50 51 public class PostConfiguration : IEntityTypeConfiguration<Post> 52 { 53 public void Configure(EntityTypeBuilder<Post> builder) 54 { 55 builder.HasKey(p => p.Id); 56 builder.Property(p => p.Title).IsRequired().HasMaxLength(300); 57 builder.HasIndex(p => p.PublishedAt); 58 } 59 } 60 61 // Query helpers 62 public class BlogQueryService 63 { 64 private readonly BlogDbContext _db; 65 66 public BlogQueryService(BlogDbContext db) => _db = db; 67 68 public async Task<List<Blog>> GetBlogsWithRecentPostsAsync(CancellationToken ct = default) 69 { 70 return await _db.Blogs 71 .AsNoTracking() 72 .Include(b => b.Posts.OrderByDescending(p => p.PublishedAt).Take(5)) 73 .AsSplitQuery() 74 .ToListAsync(ct); 75 } 76 } 77
Sign in to share your feedback and join the discussion.