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
- 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).
- 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)
- 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
Employeescollection exists inDepartment. Departmentreference exists inEmployee.
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
| Benefit | Explanation |
|---|---|
| Visual Design | Easily see and edit entities, relationships, and constraints |
| Database Generation | EF produces SQL for tables and keys automatically |
| Strong Typing | C# classes are auto-generated from the model |
| Rapid Prototyping | Quickly iterate on database design before committing |
| Easy Relationships | One-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
| Feature | Code First | Model First |
|---|---|---|
| Starting Point | C# Classes | Visual Designer / EDMX |
| Database Creation | Automatic from code | Generated from model |
| Migrations | Supported | Typically manual script updates |
| Best For | Domain-driven apps | Database-centric or visual-first apps |
| Relationships | Fluent API or Data Annotations | Designer surface |
| Refactoring | Class refactor โ migrate | Designer 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
- Create a Model First EDMX with Employee and Department.
- Define a one-to-many relationship between Department and Employees.
- Generate the database.
- Write a LINQ query to return:
- Department name
- Number of employees
- Maximum and minimum salaries
- 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.