10_Database First Approach in .NET Console Application - Maniconserve/EF-Core GitHub Wiki
Introduction
Database First is an approach in Entity Framework where the database schema is already designed, and models are generated based on the existing database. This guide explains how to implement the Database First approach in a .NET Console Application using Entity Framework Core.
Step 1: Install Required Packages
In your .NET console project, install the required EF Core packages via NuGet Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Step 2: Scaffold the Database Context and Models
Run the following command in Package Manager Console (PMC) to generate entity classes and DbContext from the database:
Scaffold-DbContext "Server=localhost\SQLEXPRESS;Database=YourDatabaseName;Trusted_Connection=True;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Before Running
This command generates:
DbContext
class (e.g.,YourDatabaseNameContext
)- Entity classes for each table in the
Models
folder
Step 3: Configure DbContext in Console Application
Modify Program.cs
to initialize DbContext
and interact with the database:
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using YourNamespace.Models;
class Program
{
static void Main()
{
using (var context = new YourDatabaseNameContext())
{
var records = context.YourTableName.ToList();
foreach (var record in records)
{
Console.WriteLine($"ID: {record.Id}, Name: {record.Name}");
}
}
}
}
Step 4: Storing Connection String Securely
Instead of hardcoding, store the connection string in appsettings.json
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=YourDatabaseName;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
Modify DbContext
to use the configuration:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
}
}
Conclusion
The Database First approach in EF Core is useful when working with an existing database. By scaffolding the DbContext and models, developers can easily integrate a database into a .NET Console application and perform CRUD operations efficiently.