| Entity Framework Core :👈 | 👉:Entity Framework Core, DB first |
ποΈ Entity Framework Core - Code First Approach |
π What is Code First?
Code First is an approach in Entity Framework Core where you define your domain models (C# classes) first, and EF Core generates the database schema from these classes. You can then use migrations to create, update, and maintain the database schema in sync with your code.
π Example in .NET Core
Hereβs a simple Code First example with EF Core:
// Install-Package Microsoft.EntityFrameworkCore
// Install-Package Microsoft.EntityFrameworkCore.SqlServer
// Install-Package Microsoft.EntityFrameworkCore.Tools
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
// Step 1: Define Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// Step 2: Define DbContext
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.;Database=CodeFirstDemo;Trusted_Connection=True;");
}
}
// Step 3: Usage
public class Program
{
public static async Task Main()
{
using var context = new AppDbContext();
// Apply migrations (from Package Manager Console):
// Add-Migration InitialCreate
// Update-Database
// 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
- Database schema evolves directly from your code.
- Great for greenfield projects (no existing DB).
- Supports migrations for schema versioning.
- Strongly typed models with LINQ queries.
- Cross-platform and works with multiple databases.
β οΈ Disadvantages
- Not ideal if you already have a complex existing database (Database First is better).
- Generated schema may not always match DBA expectations.
- Performance overhead compared to raw SQL/Dapper.
- Requires careful migration management in production.
π§ Best Practices
- Use migrations to manage schema changes safely.
- Keep DbContext scoped per request in web apps.
- Use AsNoTracking() for read-only queries.
- Combine EF Core with raw SQL/Dapper for performance-critical queries.
- Log SQL queries during development for debugging.
π Precautions
- Be cautious with lazy loading to avoid N+1 query issues.
- Secure connection strings (e.g., Azure Key Vault, user secrets).
- Ensure proper indexing in the database for large datasets.
- Test migrations in staging before applying to production.
π― Summary
EF Core Code First is ideal when starting fresh with a new project. It lets you design your domain model in C# and automatically generates the database schema. With migrations, you can evolve your schema safely while keeping your code and database in sync.
| Entity Framework Core :👈 | 👉:Entity Framework Core, DB first |