Database First Approach with Entity Framework

The Database First approach in Entity Framework (EF) allows you to generate an Entity Data Model (EDM) based on an existing database. This is particularly useful when you have a legacy database or when your database schema is designed by database administrators and you need to integrate with it using EF.

When to Use Database First

Steps to Implement Database First

1. Create a New Project and Install EF Tools

Start by creating a new .NET project (e.g., Console Application, ASP.NET Core Web Application). Then, install the necessary Entity Framework Core NuGet packages:


dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

For EF 6.x, you would use:


Install-Package EntityFramework
Install-Package EntityFramework.SqlServer

2. Scaffolding the Model from an Existing Database

You can use the EF Core command-line tools (or PMC for EF 6) to generate your model classes and DbContext from your database.

Using EF Core CLI (Recommended for EF Core):

Navigate to your project directory in the terminal and run the following command:


dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

Using Package Manager Console (EF 6 and EF Core):

Open the Package Manager Console (Tools > NuGet Package Manager > Package Manager Console) and run:


# For EF Core
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

# For EF 6.x
Scaffold-EF -Provider Microsoft.VisualStudio.TextTemplating.Walker -Output DTOs -DbContext MyDbContext -ContextDir DbContext -EntityMappingsDir Mappings -Schema dbo -Tables Customer, Order

This command will generate:

3. Using the Generated DbContext

Once the scaffolding is complete, you can use the generated DbContext to interact with your database.

Tip: It's good practice to review the generated code and make any necessary adjustments for naming conventions or relationships that EF Core might not have inferred perfectly.

using YourProject.Models; // Assuming your models are in a 'Models' folder
using Microsoft.EntityFrameworkCore;

public class Program
{
    public static void Main(string[] args)
    {
        using (var context = new MyDatabaseContext()) // Replace MyDatabaseContext with your generated DbContext name
        {
            // Example: Querying data
            var customers = context.Customers.ToList();
            foreach (var customer in customers)
            {
                Console.WriteLine($"Customer: {customer.FirstName} {customer.LastName}");
            }

            // Example: Adding data
            var newCustomer = new Customer { FirstName = "Jane", LastName = "Doe" };
            context.Customers.Add(newCustomer);
            context.SaveChanges();

            Console.WriteLine("New customer added!");
        }
    }
}

Advantages of Database First

Disadvantages of Database First

Note: For new projects where you have full control over the database schema, the Code First approach is often preferred as it allows for a more object-oriented design and seamless integration with .NET development practices.