Model First in Entity Framework

Designing Databases Visually Before Writing Code

While Code First builds databases from your C# classes, Model First takes the opposite approach: you design your database visually using an Entity Data Model (EDM), and Entity Framework generates both the database schema and the corresponding C# classes.

This approach is ideal for database-centric applications, rapid prototyping, or teams that prefer a visual schema design workflow.


๐Ÿ”น What Is Model First?

Model First lets you:

  • Define entities, relationships, and constraints graphically in the Entity Framework Designer.
  • Generate SQL scripts to create a database schema automatically.
  • Produce C# classes that match your visual model for use in your application.

โœ… Combines the clarity of visual modelling with the power of EFโ€™s ORM features.


๐Ÿ”น Setting Up Model First

  1. Create an Entity Data Model (EDMX)
  • In Visual Studio:
    • Right-click your project โ†’ Add โ†’ New Item โ†’ ADO.NET Entity Data Model
    • Choose Empty Model (Model First).
  1. Design Your Model
  • Drag entities onto the design surface.
  • Add properties (columns) and set types.
  • Define primary keys and relationships (one-to-many, many-to-many).

Example visual design:

  • Department entity: Id (PK), Name
  • Employee entity: Id (PK), Name, Salary, DepartmentId (FK)
  1. Generate Database from Model
  • Right-click the designer surface โ†’ Generate Database from Model.
  • EF produces SQL scripts to create tables, constraints, and relationships.

๐Ÿ”น Generated C# Classes

Model First automatically generates DbContext and entity classes.

Example:

public partial class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }

    public int DepartmentId { get; set; }
    public virtual Department Department { get; set; }
}

public partial class Department
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

โœ… Classes include navigation properties, foreign keys, and collections.


๐Ÿ”น Relationships and Navigation

One-to-Many:

  • Department โ†’ Employees
  • EF ensures Employees collection exists in Department.
  • Department reference exists in Employee.

Many-to-Many:

  • Use the designer to link two entities.
  • EF generates a join table automatically.

โœ… Visual modeling reduces errors and ensures relationships are consistent.


๐Ÿ”น Querying Model First Data

Once the database is generated and classes created, querying is the same as Code First:

using (var context = new CompanyEntities()) // auto-generated context
{
    var highEarners = context.Employees
        .Where(e => e.Salary > 50000)
        .OrderByDescending(e => e.Salary)
        .ToList();

    foreach (var emp in highEarners)
        Console.WriteLine($"{emp.Name} - ยฃ{emp.Salary}");
}

Output:

Alice - ยฃ60000

โœ… Strongly-typed LINQ queries work seamlessly with Model First entities.


๐Ÿ”น Advantages of Model First

BenefitExplanation
Visual DesignEasily see and edit entities, relationships, and constraints
Database GenerationEF produces SQL for tables and keys automatically
Strong TypingC# classes are auto-generated from the model
Rapid PrototypingQuickly iterate on database design before committing
Easy RelationshipsOne-to-many and many-to-many associations are straightforward

๐Ÿ”น Updating the Model

  • Make changes in the EDMX designer.
  • Generate an updated SQL script to evolve the database.
  • Regenerate classes if needed.

โœ… Allows database-first evolution while keeping code in sync.


๐Ÿ”น Real-World Example โ€“ Department Salary Summary

using (var context = new CompanyEntities())
{
    var report = context.Employees
        .GroupBy(e => e.Department.Name)
        .Select(g => new
        {
            Department = g.Key,
            EmployeeCount = g.Count(),
            AverageSalary = g.Average(x => x.Salary)
        });

    foreach (var dept in report)
        Console.WriteLine($"{dept.Department}: {dept.EmployeeCount} staff, avg ยฃ{dept.AverageSalary:F0}");
}

Output:

IT: 2 staff, avg ยฃ62500
HR: 2 staff, avg ยฃ43500
Finance: 1 staff, avg ยฃ50000

โœ… Same LINQ syntax as Code First โ€” Model First is fully compatible with EFโ€™s querying features.


๐Ÿ”น Comparison: Code First vs Model First

FeatureCode FirstModel First
Starting PointC# ClassesVisual Designer / EDMX
Database CreationAutomatic from codeGenerated from model
MigrationsSupportedTypically manual script updates
Best ForDomain-driven appsDatabase-centric or visual-first apps
RelationshipsFluent API or Data AnnotationsDesigner surface
RefactoringClass refactor โ†’ migrateDesigner change โ†’ regenerate

๐Ÿ”น Best Practices

  • Keep the model clean and normalized.
  • Use partial classes for custom logic without breaking generated code.
  • Generate the database before deploying to production.
  • Track changes carefully; regenerating classes overwrites manual edits.
  • Combine with LINQ for queries, filtering, grouping, and projections.

๐Ÿงช Challenge Task

  1. Create a Model First EDMX with Employee and Department.
  2. Define a one-to-many relationship between Department and Employees.
  3. Generate the database.
  4. Write a LINQ query to return:
    • Department name
    • Number of employees
    • Maximum and minimum salaries
  5. Display results like:
    "IT: 2 staff, max ยฃ65000, min ยฃ60000"

๐Ÿ‘จโ€๐Ÿ’ป Want More?

Our C# Mastery Course covers:

  • Code First, Model First, and Database First approaches
  • LINQ queries, projections, and joins
  • Migrations, seeding, and schema evolution
  • Best practices for maintainable, data-driven applications

Master Model First to visualize, design, and deploy databases effortlessly, while leveraging EFโ€™s full C# integration and LINQ querying power.