Previous Entity Framework Core, code first Entity Framework Core Model First Next

🗄️ Entity Framework Core - Database First Approach

📖 What is Database First?

Database First is an approach in EF Core where the database schema already exists, and EF Core generates the DbContext and entity classes from that schema. This is useful when working with legacy databases or when the database is designed and maintained by DBAs.

🛠 Example in .NET Core

Steps to implement Database First in EF Core:

  1. Create or use an existing database (e.g., SQL Server).
  2. Install required NuGet packages:
    • Microsoft.EntityFrameworkCore.SqlServer
    • Microsoft.EntityFrameworkCore.Tools
  3. Run the following command in the Package Manager Console:
Scaffold-DbContext "Server=.;Database=DemoDb;Trusted_Connection=True;" 
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
    

This generates entity classes and a DbContext based on the database schema.

Generated Example

// Example entity generated from database
public partial class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Example DbContext
public partial class DemoDbContext : DbContext
{
    public virtual DbSet<Product> Products { get; set; }

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

✅ Advantages

  • Ideal for existing or legacy databases.
  • Database schema is the single source of truth.
  • Quickly generates models and context from schema.
  • Good for teams where DBAs manage schema separately.

⚠️ Disadvantages

  • Schema changes require re-scaffolding or manual updates.
  • Less flexibility compared to Code First migrations.
  • Generated code may need customization (partial classes help).
  • Not as smooth for agile schema evolution.

🧭 Best Practices

  • Use partial classes to extend generated entities without losing changes on re-scaffold.
  • Keep the DbContext scoped per request in web apps.
  • Use AsNoTracking() for read-only queries to improve performance.
  • Regenerate models when schema changes, and track changes in version control.

🔒 Precautions

  • Secure connection strings (e.g., user secrets, Azure Key Vault).
  • Be cautious with lazy loading to avoid N+1 query issues.
  • Ensure proper indexing in the database for performance.
  • Test re-scaffolding in a safe environment before applying to production.

🎯 Summary

EF Core Database First is best when working with an existing database schema. It allows developers to scaffold models and DbContext directly from the database, making it ideal for legacy systems or DBA-driven environments. While it lacks the flexibility of Code First migrations, it ensures tight alignment with the database design.

Back to Index
Previous Entity Framework Core, code first Entity Framework Core Model First Next
*