Query a Database with Entity Framework
Use Entity Framework and LINQ to Connect to and Query an Existing Database
Updated: 23 December 2025
Info derived from this post on LearnEntityFrameworkCore
Sometimes you want to use a database but don’t want to deal with the difficulties created by SQL
Setting Up
Create Project
First, you will need a database to connect to, this can be done by any method, but I will use the Northwind database for this. The SQL Setup Script can be found here
Once that’s done you can create a new project for running or queries
1dotnet new console -n DBPlaygroundAdd Packages
You will also need some packages installed on your application to make this all work
1dotnet add package Microsoft.EntityFrameworkCore.SqlServer2dotnet add package Microsoft.EntityFrameworkCore.DesignAdd EF Global
And you’ll also need to install the ef tool if you don’t already have it:
1dotnet tool install --global dotnet-efScaffold Models
Now that you have everything installed, you can go ahead and run the following to scaffold your code models. I am connecting to SQLEXPRESS on the Northwind database but you can use any connection string that works for your purpose
1dotnet ef dbcontext scaffold "Server=localhost\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o ModelThe above will output generated models that align to the data in your database in the Models folder
Using the Connection
When we ran the above it will have generated a DBContext file. In our case NorthwindContext which is the class for our Database. We can use this as follows:
1using System;2using System.Linq;3using DBPlayground.Model;4
5namespace DBPlayground6{7 class Program8 {9 static void Main(string[] args)10 {11 var db = new NorthwindContext();12 }13 }14}We can thereafter use the db instance to do database things using EF
1db.Customers2 .Take(5)3 .ToList()4 .ForEach(c => Console.WriteLine($"{c.ContactName}\t{c.Country}"));