Previous Entity Framework Core, DB first Repository pattern Next

🗄️ Entity Framework Core - Model First (via Code First + Migrations)

📖 What is Model First?

In classic EF6, Model First meant designing a model diagram (EDMX) and generating both the database and classes from it. In EF Core, there is no EDMX designer, but you can achieve a similar workflow by defining your domain model classes first and then generating the database schema using migrations.

🛠 Example in .NET Core

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

using Microsoft.EntityFrameworkCore;

// Step 1: Define Model
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

// Step 2: Define DbContext
public class SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }

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

// Step 3: Apply Migrations
// From Package Manager Console:
// Add-Migration InitialCreate
// Update-Database
    

✅ Advantages

  • Database schema evolves directly from your model classes.
  • Strongly typed models with LINQ queries.
  • Cross-platform and works with multiple databases.
  • Supports migrations for schema versioning.

⚠️ Disadvantages

  • No visual designer (unlike EF6 EDMX).
  • Generated schema may not always match DBA expectations.
  • Requires careful migration management in production.

🧭 Best Practices

  • Use Fluent API for complex relationships and constraints.
  • 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.

🔒 Precautions

  • Secure connection strings (e.g., user secrets, Azure Key Vault).
  • Be cautious with lazy loading to avoid N+1 query issues.
  • Test migrations in staging before applying to production.

🎯 Summary

EF Core does not have a true Model First designer like EF6, but you can achieve the same effect by defining your model classes first and generating the database schema with migrations. This approach is widely used in modern .NET Core applications.

Back to Index
Previous Entity Framework Core, DB first Repository pattern Next
*