Introduction
Many Entity Framework Core problems are not caused by one isolated typo. They often result from an inconsistency between the .NET SDK, EF Core packages, SQL Server connection, entity model, migration history and DbContext lifetime. When these layers are not checked separately, the first exception message may hide the real root cause.
In this lesson, we will build a small and consistent troubleshooting laboratory that can be reused throughout the course. The application connects to a SQL Server database named EfTroubleshootingLab and performs basic CRUD operations for categories and products. We will also create intentionally flawed examples and correct them by separating package, connection and relational problems.
EF Core 10 requires the .NET 10 SDK to build and the .NET 10 runtime to run. EF Core 10 was released in November 2025 and is an LTS release supported until November 10, 2028. Keeping all EF Core packages in the same major version is therefore an essential first diagnostic step.
1. Laboratory goals and structure
By the end of the setup, the laboratory should contain the following:
- A .NET 10 Console App created in Visual Studio 2022.
- The
Microsoft.EntityFrameworkCore.SqlServerprovider. - EF Core design-time and tools packages for migrations.
CategoryandProductentity classes.- An
AppDbContextthat manages a one-to-many relationship. - Basic create, read, update and delete operations.
- SQL logging and detailed development-time diagnostics.
The purpose is not to create a complex architecture. A small application is easier to inspect when an error occurs. In later lessons, this same project can be used to reproduce tracking conflicts, relationship errors, migration problems, inefficient queries and transaction issues.
2. Create the project and install packages
Open Visual Studio 2022 and create a Console App named EfTroubleshootingLab. Select .NET 10.0 as the target framework. Add the following packages from the terminal or the NuGet Package Manager:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.*
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.*
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 10.0.*The asterisk is used here as an instructional notation for the latest patch within the 10.0 family. In a real project, pin package versions explicitly and keep every EF Core package on the same version line. The SQL Server package provides the database provider, the Design package supports design-time operations, and the Tools package enables migration commands in Visual Studio.
Verify the SDK and package state:
dotnet --version
dotnet list packageThe SDK should report a 10.x version, and the EF Core packages should belong to the 10.x family. If one package is 9.x or 8.x, correct the package references before creating migrations. Version mismatches can produce build errors, design-time failures or behavior that is difficult to reproduce.
3. Define the entity models
Add a Models folder and create Category.cs:
using System.ComponentModel.DataAnnotations;
namespace EfTroubleshootingLab.Models;
public class Category
{
public int Id { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; } = string.Empty;
public ICollection<Product> Products { get; set; } = new List<Product>();
}Now create Product.cs:
using System.ComponentModel.DataAnnotations;
namespace EfTroubleshootingLab.Models;
public class Product
{
public int Id { get; set; }
[Required, MaxLength(150)]
public string Name { get; set; } = string.Empty;
[Range(typeof(decimal), "0.01", "1000000")]
public decimal Price { get; set; }
public int CategoryId { get; set; }
public Category? Category { get; set; }
}This model represents a one-to-many relationship: one category can contain many products. CategoryId is the foreign key, Category is the reference navigation property, and Products is the collection navigation property. A nullable navigation property does not mean that EF Core automatically loads the category whenever a product is queried. Loading related data must be configured or requested explicitly, a distinction that will matter when we study Include and navigation-property issues.
4. Configure DbContext and the connection string
Add a Data folder and create AppDbContext.cs:
using EfTroubleshootingLab.Models;
using Microsoft.EntityFrameworkCore;
namespace EfTroubleshootingLab.Data;
public class AppDbContext : DbContext
{
public DbSet<Category> Categories => Set<Category>();
public DbSet<Product> Products => Set<Product>();
protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseSqlServer(
"Server=(localdb)\\MSSQLLocalDB;Database=EfTroubleshootingLab;Trusted_Connection=True;TrustServerCertificate=True")
.LogTo(Console.WriteLine)
.EnableDetailedErrors();
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>()
.HasMany(c => c.Products)
.WithOne(p => p.Category)
.HasForeignKey(p => p.CategoryId)
.OnDelete(DeleteBehavior.Restrict);
}
}This example uses SQL Server LocalDB. If you use SQL Server Express or a remote SQL Server instance, change only the connection string to match your environment. Do not place production passwords in source code. Use User Secrets, environment variables or an appropriate secret-management service instead.
LogTo writes EF Core log messages to the console. EnableDetailedErrors can provide more diagnostic detail and should normally be enabled only during development or controlled troubleshooting. We have not enabled EnableSensitiveDataLogging in the base example because parameter values may contain confidential information. Use it only temporarily in a secure development environment.
5. Create and apply the migration
Open Tools > NuGet Package Manager > Package Manager Console in Visual Studio. Select the correct project as the Default Project and run:
Add-Migration InitialCreate
Update-DatabaseAlternatively, use the command-line tools:
dotnet ef migrations add InitialCreate
dotnet ef database updateThe first command creates migration files from the model. The second applies the migration to SQL Server. If you receive a Build failed message, run dotnet build first and fix namespace errors, missing packages or project-selection problems before retrying the EF command.
When a project targets multiple frameworks, EF Core 10 tools may require an explicit framework selection. In that situation, use a command such as dotnet ef database update --framework net10.0. This laboratory targets one framework, so the standard commands are sufficient.
6. Implement basic CRUD operations
Replace the contents of Program.cs with the following example:
using EfTroubleshootingLab.Data;
using EfTroubleshootingLab.Models;
using Microsoft.EntityFrameworkCore;
using var db = new AppDbContext();
if (!await db.Categories.AnyAsync())
{
var hardware = new Category { Name = "Hardware" };
db.Categories.Add(hardware);
await db.SaveChangesAsync();
db.Products.AddRange(
new Product { Name = "Mechanical Keyboard", Price = 1200, CategoryId = hardware.Id },
new Product { Name = "USB Microphone", Price = 1800, CategoryId = hardware.Id });
await db.SaveChangesAsync();
}
var products = await db.Products
.OrderBy(p => p.Name)
.Select(p => new
{
p.Id,
p.Name,
p.Price,
CategoryName = p.Category!.Name
})
.ToListAsync();
foreach (var product in products)
{
Console.WriteLine($"{product.Id} - {product.Name} - {product.Price:C} - {product.CategoryName}");
}AnyAsync checks whether at least one record exists. After SaveChangesAsync, the database-generated key is available in hardware.Id. The final query uses a projection with Select so that only the required fields are returned. This reduces unnecessary data transfer and establishes a good baseline for later performance analysis.
7. Intentional errors and root-cause analysis
Error 1: Package version mismatch
Suppose the SQL Server provider is version 10.x while the Design package is version 9.x. Migration commands may fail or produce confusing design-time errors. First inspect the package list:
dotnet list package
dotnet remove package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.*The key lesson is to diagnose the toolchain before diagnosing the model. If the compiler and design-time services do not use compatible package versions, later SQL or relationship investigations are unreliable.
Error 2: Invalid connection string
The following connection string will not work on a machine where LocalDB is unavailable:
Server=(localdb)\MSSQLLocalDB;Database=EfTroubleshootingLab;Trusted_Connection=True;Check that the SQL Server service exists, the instance name is correct and the database connection can be established from SQL Server Management Studio or another independent client. Testing the same connection outside EF Core helps determine whether the root cause belongs to EF Core or to SQL Server, credentials or the local environment.
Error 3: Invented foreign key value
db.Products.Add(new Product
{
Name = "Invalid Product",
Price = 100,
CategoryId = 999
});
await db.SaveChangesAsync();If category 999 does not exist, SQL Server returns a foreign key violation. Query a valid category first or establish the relationship through the navigation property:
var category = await db.Categories.FirstAsync(c => c.Name == "Hardware");
var product = new Product
{
Name = "Valid Product",
Price = 100,
Category = category
};
db.Products.Add(product);
await db.SaveChangesAsync();Instead of catching and hiding the exception, inspect the foreign key value, verify the related row in the database and compare the current migration schema with the model. Systematic troubleshooting means checking each of these independently.
8. Troubleshooting checklist
- Does the project target
net10.0? - Are all EF Core packages in the 10.x family?
- Is SQL Server or LocalDB running?
- Are the server and database names in the connection string correct?
- Was the migration created and applied?
- Does the migration schema match the current entity model?
- Do foreign key values refer to real rows?
- Do the SQL logs show the expected connection and queries?
- Is sensitive-data logging disabled outside a controlled development environment?
9. Short practice exercise
Add a new Supplier entity to the laboratory. A product should have an optional supplier. Before creating a migration, answer these questions:
- What will be the primary key of the Supplier entity?
- Which foreign key and navigation property should be added to Product?
- Should deleting a supplier delete its products or prevent the operation?
- How will you inspect the schema changes before applying the migration?
Create the migration, apply it and write a projection that lists products together with the supplier name. Then temporarily use an invalid supplier key and observe the exception. Explain whether the problem belongs to the model, the database data or the migration state.
When should I use this approach?
This small Console App approach is useful when learning EF Core, isolating migration problems, testing provider or package compatibility and reducing a production issue to a minimal reproducible example. In a larger application, move the connection string into configuration, use dependency injection for DbContext registration and separate development, test and production settings.
Conclusion
In this lesson, we built a consistent SQL Server laboratory with EF Core 10 and .NET 10. We defined entities with Data Annotations, configured a one-to-many relationship, created a DbContext, applied a migration and implemented basic asynchronous CRUD operations. We also separated package mismatch, connection and foreign key errors by analyzing their root causes rather than hiding their exceptions.
In the next lessons, this same project will be used to investigate DbContext lifetime and Entity Tracking problems. Keep the same diagnostic sequence: verify the SDK and package versions, validate the environment, compare the model with the database, and inspect the generated SQL and exception details.
Sources
- https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew
- https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/breaking-changes
- https://learn.microsoft.com/en-us/ef/core/providers/sql-server/
- https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/simple-logging
- https://learn.microsoft.com/en-us/ef/core/get-started/overview/install