Introduction
In Day 11, we learned how to connect SQL Server with a .NET Web API using Entity Framework Core. We configured the connection string, registered DbContext, and used migrations to create and update the database.
Now, let's understand two important approaches for working with databases in Entity Framework Core:
Code First
Database First
Both approaches help us work with SQL Server through Entity Framework Core, but they differ in where we start: our C# code or an existing database.
Understanding these approaches will help you choose the right database development strategy for your project.
1. What Is Code First?
In the Code First approach, we start by writing C# classes and defining our database structure in the application.
Entity Framework Core uses these classes and the DbContext configuration to generate database tables and relationships.
In simple words:
First, we write C# code. Then, Entity Framework Core creates or updates the database structure.
Code First Workflow
Create entity classes.
Create the
DbContextclass.Configure relationships and constraints.
Create a migration.
Apply the migration to SQL Server.
Entity Framework Core creates or updates the database schema.
Example: Employee Entity
Let's create an Employee entity.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public decimal Salary { get; set; }
}Create ApplicationDbContext
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}Here:
DbContextrepresents the database session.DbSet<Employee>represents the Employee entity collection.Entity Framework Core uses this configuration to map the entity to a database table.
Create and Apply Migration
Open the Package Manager Console or terminal and execute:
dotnet ef migrations add InitialCreateThis command creates a migration based on the current model.
Now apply the migration:
dotnet ef database updateEntity Framework Core applies the migration to SQL Server and creates the required database objects.
Important: The SQL Server connection must be configured, and the database user must have the necessary permissions.
2. What Is Database First?
In the Database First approach, we already have a database and its tables.
Instead of creating the database from C# classes, we generate C# entity classes and a DbContext from the existing database schema.
In simple words:
First, the database exists. Then, Entity Framework Core generates the corresponding C# code.
This approach is useful when:
The database already exists.
Database design is managed by a DBA or another team.
You are integrating an existing legacy application.
You need to work with an established database structure.
Database First Workflow
Create or identify an existing SQL Server database.
Configure the database connection.
Run the Entity Framework Core scaffolding command.
Entity Framework Core reads the database schema.
It generates entity classes and a
DbContext.Use the generated classes in your application.
Example: Generate Models from an Existing Database
Suppose we already have a SQL Server database named EmployeeDB containing an Employees table.
First, install the required packages if they are not already installed:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.DesignNow execute the scaffolding command:
dotnet ef dbcontext scaffold "Server=YOUR_SERVER_NAME;Database=EmployeeDB;Trusted_Connection=True;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -c ApplicationDbContextThis command generates:
Entity classes inside the
Modelsfolder.An
ApplicationDbContextclass.Database mappings based on the existing schema.
Note: Replace YOUR_SERVER_NAME with your actual SQL Server instance name. The connection string shown is intended for a local development setup. Use secure connection settings for production.
3. Code First vs Database First: Key Differences
Let's compare both approaches.
| Feature | Code First | Database First |
|---|---|---|
| Starting point | C# classes | Existing database |
| Database creation | Through migrations | Database already exists |
| Entity classes | Written manually | Generated through scaffolding |
| Schema management | Usually managed through migrations | Based on the existing database |
| Best suited for | New applications | Existing databases |
| Database changes | Update models and create migrations | Update database and regenerate or adjust models |
| Developer control | Code-driven | Database-driven |
4. Advantages of Code First
Some important advantages of Code First are:
1. Code-driven development
Developers can define entities, relationships, and constraints directly in C#.
2. Migration support
Entity Framework Core migrations help track and apply database schema changes.
3. Better integration with application code
Entity classes are maintained alongside the application.
4. Suitable for new projects
It is a convenient approach when the database structure is being designed as part of application development.
5. Advantages of Database First
Some important advantages of Database First are:
1. Works with existing databases
You can integrate Entity Framework Core into an application without creating the database from scratch.
2. Database control
Database administrators can manage the database structure independently of application development.
3. Faster initial model generation
Entity Framework Core can generate entity classes and the context from an existing schema.
4. Useful for legacy applications
It is suitable when an organization already has a mature SQL Server database.
6. When Should You Use Code First?
Consider Code First when:
You are developing a new application.
Your application team manages the database structure.
You want to use Entity Framework Core migrations.
You prefer defining database models in C#.
Your database schema evolves with application requirements.
Example: You are developing a new Employee Management Web API. You create Employee, Department, and Designation classes and use migrations to create their database tables.
7. When Should You Use Database First?
Consider Database First when:
Your organization already has a SQL Server database.
Database design is managed by a separate team.
You are integrating an existing database into a new Web API.
You are working with a legacy application.
You need to generate entity classes from an established schema.
Example: Your company already has an EmployeeDB database with hundreds of tables. You need to develop a new .NET Web API using that database. Database First can help generate the initial entity classes and DbContext.
8. Can We Use Both Approaches in the Same Project?
Yes, but you should carefully manage the database schema and model changes.
For example:
You can scaffold an existing database to generate entity classes.
You can later manage selected model changes through migrations.
You can also use custom configurations and manually maintain generated code.
However, mixing database-first scaffolding and migrations requires a clear strategy. Otherwise, schema changes can become difficult to track and maintain.
For generated files, consider using separate partial classes or configuration files so that custom code is not overwritten during re-scaffolding.
9. Important Entity Framework Core Commands
Here are some useful commands for both approaches.
Code First commands
# Create a migration
dotnet ef migrations add InitialCreate
# Apply migrations to the database
dotnet ef database update
# View migration list
dotnet ef migrations list
# Generate SQL script
dotnet ef migrations scriptDatabase First command
# Generate entity classes and DbContext
dotnet ef dbcontext scaffold "YOUR_CONNECTION_STRING" Microsoft.EntityFrameworkCore.SqlServer -o ModelsThese commands are useful when working with Entity Framework Core in real-world applications.
10. Best Practices
Choose a database development approach based on your project requirements.
Use meaningful entity and table names.
Keep database credentials out of source control.
Review migration files before applying them.
Take database backups before production schema changes.
Avoid manually modifying generated files without a clear regeneration strategy.
Keep Entity Framework Core package versions compatible.
Use separate configurations for development, testing, and production.
Conclusion
Code First and Database First are two different approaches for working with databases in Entity Framework Core.
With Code First, we define our database structure through C# classes and use migrations to create or update the database.
With Database First, we start with an existing database and generate entity classes and DbContext using scaffolding.
Neither approach is universally better. The right choice depends on your application requirements, existing database structure, and development workflow.
Understanding both approaches is important for building and maintaining real-world .NET Web API applications.
What's Next?
Day 13 – Global Exception Handling
In the next article, we'll explore how to implement global exception handling in .NET Web API, handle unexpected errors centrally, and return consistent error responses to clients.
Skills Tutorials – Learn • Build • Grow Together
Continue learning with our 30-day .NET Core Web API series.
No comments:
Post a Comment