Previous Dead Letter Queues Entity Framework Core, code first Next

πŸ—„οΈ Entity Framework Core (EF Core)

πŸ“– What is EF Core?

Entity Framework Core (EF Core) is a modern, lightweight, open-source, and cross-platform Object-Relational Mapper (ORM) for .NET. It allows developers to interact with databases using strongly typed C# objects instead of writing raw SQL queries. EF Core supports multiple database providers such as SQL Server, PostgreSQL, MySQL, SQLite, and Cosmos DB.

πŸ›  Example in .NET Core

Here’s a simple example of using EF Core with a DbContext and a model:

// Install-Package Microsoft.EntityFrameworkCore
// Install-Package Microsoft.EntityFrameworkCore.SqlServer

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

// Model
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// DbContext
public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=.;Database=DemoDb;Trusted_Connection=True;");
    }
}

// Usage
public class Program
{
    public static async Task Main()
    {
        using var context = new AppDbContext();

        // Create
        context.Products.Add(new Product { Name = "Laptop", Price = 1200 });
        await context.SaveChangesAsync();

        // Read
        var products = await context.Products.ToListAsync();
        foreach (var p in products)
            Console.WriteLine($"{p.Id}: {p.Name} - {p.Price}");
    }
}
    

βœ… Advantages

  • Eliminates most boilerplate SQL code.
  • Cross-platform and open-source.
  • Supports LINQ queries for type safety and readability.
  • Works with multiple relational and NoSQL databases.
  • Supports migrations for schema evolution.

⚠️ Disadvantages

  • Performance overhead compared to raw SQL or Dapper.
  • Complex queries may be harder to optimize.
  • Learning curve for advanced features (tracking, lazy loading, etc.).
  • Not always the best fit for high-performance analytics workloads.

🧭 Best Practices

  • Use AsNoTracking() for read-only queries to improve performance.
  • Keep DbContext lifetime short (scoped per request in web apps).
  • Use migrations to manage schema changes safely.
  • Log generated SQL for debugging and optimization.
  • Combine EF Core with raw SQL/Dapper for performance-critical queries.

πŸ”’ Precautions

  • Validate input to prevent SQL injection (even though EF Core parameterizes queries).
  • Be cautious with lazy loading to avoid N+1 query problems.
  • Monitor database connections and transaction usage.
  • Ensure proper indexing in the database for large datasets.

🎯 Summary

EF Core is a powerful ORM that simplifies database access in .NET applications. It’s ideal for CRUD-heavy applications, microservices, and enterprise systems. With proper optimization and best practices, EF Core balances productivity with performance in modern .NET development.

⚑ Entity Framework Approaches (Short Summary)

  • Code First πŸ“ - Define C# classes first. - EF generates the database schema via migrations. - Best for new projects where code drives the DB.
  • Database First πŸ—„οΈ - Start with an existing database. - EF scaffolds DbContext and entity classes. - Best for legacy or DBA-managed databases.
  • Model First 🎨 (EF6 only, not EF Core) - Design a visual model (EDMX). - EF generates both DB schema and classes. - Replaced in EF Core by Code First + Migrations.

🎯 Quick Takeaway

- Use Code First for new, agile projects. - Use Database First when working with an existing schema. - Model First is legacy (EF6), not supported in EF Core.

EF Core: Code First vs Database First vs Model First

πŸ“Š Comparison Table

Aspect Code First Database First Model First (Classic EF6)
Definition Define C# classes first, EF generates database schema via migrations. Start with an existing database, scaffold DbContext and entities. Design a visual model (EDMX), EF generates both DB schema and classes.
Best For Greenfield projects, agile schema evolution. Legacy databases, DBA-driven environments. Visual-first design, teams preferring diagrams.
Tooling Migrations (Add-Migration, Update-Database). Scaffold-DbContext command. EDMX Designer (not available in EF Core).
Flexibility High β€” schema evolves with code. Low β€” schema changes require re-scaffolding. Medium β€” schema tied to visual model.
Supported in EF Core? βœ… Yes βœ… Yes ❌ No (only in EF6, not EF Core)
Advantages Strongly typed, migrations, agile-friendly. Aligns with existing DB, quick setup for legacy systems. Visual modeling, auto-generation of DB + classes.
Disadvantages Not ideal for existing DBs, requires migration discipline. Less flexible, generated code may need customization. No longer supported in EF Core, limited to EF6.

🎯 Summary

- Use Code First when starting fresh and you want your C# models to drive the database. - Use Database First when working with an existing schema or DBA-managed database. - Model First was available in EF6 with EDMX diagrams, but is not supported in EF Core. In EF Core, β€œModel First” is effectively achieved through Code First + Migrations.

Back to Index
Previous Dead Letter Queues Entity Framework Core, code first Next
*