How to Add Entity Framework Core DBContext in .NET Core Console Application
Entity Framework Core helps to add the DBContext file and all the models into the .NET Core project, and using Dependency Injection in .NET Core we can perform the CRUD operation using Entity Framework Core, following steps help to add Entity Framework Core DBContext file and list of Models using Scaffold DbContext and use the .NET Core to use the DBContext object to perform DB operations:
Step 1: Create .NET Core console application using below .NET CLI command or using Visual Studio Editor:
dotnet new console -o EFCoreDBContextApplication
Using above command, it creates .NET Core console application in the "EFCoreDBContextApplication" output directory
Step 2: Add the required NuGet Packages:
First change the directory to Project directory:
cd EFCoreDBContextApplication
Now add the required NuGet packages through following .NET CLI commands:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.Extensions.DependencyInjection
Step 3: Now, the next step is to Scaffold the DbContext and Models from already created database, to begin with, install the required .NET CLI tools: In the below command we are installing dotnet ef tool globally.
dotnet tool install --global dotnet-ef
Now, run the DBContext scaffhold .NET CLI command:
dotnet ef dbcontext scaffold "Server=localhost\SQLEXPRESS;Database=testdb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models
OR Generate DBContext and Models Using Powershell / Nuget Package Manager Console by running following command:
Scaffold-DbContext "Server=localhost\SQLEXPRESS;Database=testdb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Above dbcontext scaffold command will create the Models folder with all the tables inside the testdb database will be created as Model files in Models folder
After database Scaffold, the project structure files looks like following:
Step 4: Now, create new C# class file OrderService.cs and write the below code to DisplayOrders on the Console Output window:
using EFCoreDBContextApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace EFCoreDBContextApplication
{
class OrderService
{
private testdbContext _dbContext;
public OrderService(testdbContext context)
{
_dbContext = context;
}
public void DisplayOrders()
{
var OrdersList = (from order in _dbContext.Orders
join product in _dbContext.Products on order.ProductId equals product.ProductId
join customer in _dbContext.Customers on order.CustomerId equals customer.CustomerId
select new
{
CustomerName = customer.Name,
ProductName = product.Name,
OrderDate = order.OrderDate,
Quantity = order.Quantity,
Price = order.Price
}).ToList();
foreach (var order in OrdersList)
{
Console.WriteLine($"Order Details are: Customer Name: {order.CustomerName}; Product Name: {order.ProductName}; Order Date: {order.OrderDate}; Qntity: {order.Quantity}; Price: {order.Price}");
}
}
}
}
Step 5: Now, add the following code in Program.cs file to register the OrderService and call its DisplayOrders() methods from Main method
using EFCoreDBContextApplication.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace EFCoreDBContextApplication
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=testdb;Trusted_Connection=True;";
var services = new ServiceCollection();
services.AddSingleton<OrderService>();
services.AddDbContext<testdbContext>(options => options.UseSqlServer(connectionString));
ServiceProvider serviceProvider = services.BuildServiceProvider();
var testService = serviceProvider.GetService<OrderService>();
testService.DisplayOrders();
Console.ReadLine();
}
}
}
Step 6: Now, run the program use the below .NET CLI command to run the project:
dotnet run
Output is: