When you first scaffold a database into an ASP.NET Core Web API, it's tempting to return your EF Core entities straight out of the controller. It works, until it doesn't: you leak columns you never meant to expose, navigation properties cause circular-reference errors, and any change to the database schema becomes a breaking change for every client.

In this post I'll take a working bike shop API (built on the classic BikeStores sample database) and:

  1. Remove the template junk (WeatherForecast)
  2. Introduce a DTO (Data Transfer Object) for products
  3. Wire up AutoMapper to convert entities → DTOs
  4. Add a small business-intelligence (BI) endpoint that returns computed stats for a category

From the outside, the product endpoints won't change at all. That's the whole point.

What we're building

Product endpoints (shape after the refactor):

{ "productId": 81, "productName": "Electra Amsterdam Fashion 7i Ladies' - 2017", "brandName": "Electra", "categoryName": "Cruisers Bicycles", "modelYear": 2017, "listPrice": 1099.99 } 

New BI endpoint: GET /api/BI/Category/4

{ "categoryId": 4, "categoryName": "Cruisers Bicycles", "productCount": 14, "currentStockCount": 306, "storeCount": 3 } 

Prerequisites

  • .NET 10 SDK (dotnet --version)
  • SQL Server / LocalDB with the BikeStores sample database restored
  • The EF Core CLI tool:
dotnet tool install --global dotnet-ef # or, if you already have it dotnet tool update --global dotnet-ef 

Step 0: Starting point (if you're building from scratch)

If you already have a bike shop API with a products controller, skip ahead to Step 1. Otherwise, here's how to get to the starting line.

mkdir PedalShop && cd PedalShop dotnet new webapi --use-controllers -n PedalShop.Api cd PedalShop.Api dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Design dotnet add package Microsoft.EntityFrameworkCore.Tools 

Add a connection string to appsettings.json:

{ "ConnectionStrings": { "PedalShopDb": "Server=(localdb)\\MSSQLLocalDB;Database=BikeStores;Trusted_Connection=True;TrustServerCertificate=True" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" } 

Scaffold the entities and DbContext from the existing database:

dotnet ef dbcontext scaffold "Name=ConnectionStrings:PedalShopDb" Microsoft.EntityFrameworkCore.SqlServer --output-dir Models --context PedalShopContext --no-onconfiguring 

This generates Models/Product.cs, Models/Brand.cs, Models/Category.cs, Models/Stock.cs, Models/Store.cs (and a few others) plus Models/PedalShopContext.cs.

The bits we care about look roughly like this:

// Models/Product.cs (scaffolded) public partial class Product { public int ProductId { get; set; } public string ProductName { get; set; } = null!; public int BrandId { get; set; } public int CategoryId { get; set; } public short ModelYear { get; set; } public decimal ListPrice { get; set; } public virtual Brand Brand { get; set; } = null!; public virtual Category Category { get; set; } = null!; public virtual ICollection<Stock> Stocks { get; set; } = new List<Stock>(); } // Models/Stock.cs (scaffolded) public partial class Stock { public int StoreId { get; set; } public int ProductId { get; set; } public int? Quantity { get; set; } public virtual Product Product { get; set; } = null!; public virtual Store Store { get; set; } = null!; } 

Step 1: Clean out the template

The webapi template ships with a demo WeatherForecast. Delete it:

# PowerShell Remove-Item .\WeatherForecast.cs Remove-Item .\Controllers\WeatherForecastController.cs # bash rm WeatherForecast.cs Controllers/WeatherForecastController.cs 

Also open PedalShop.Api.http and remove the GET {{PedalShop.Api_HostAddress}}/weatherforecast/ request so it doesn't confuse you later.

Step 2: Create a DTOs folder and the product DTO

Create a DTOs folder at the same level as Models and Controllers:

PedalShop.Api/ ├── Controllers/ ├── DTOs/ <-- new ├── Mapping/ <-- new (for the AutoMapper profile) ├── Models/ └── Program.cs 
mkdir DTOs mkdir Mapping 

DTOs/BikeProductDto.cs:

namespace PedalShop.Api.DTOs; /// <summary> /// The public shape of a product. Flat, no navigation properties, /// nothing the client doesn't need. /// </summary> public class BikeProductDto { public int ProductId { get; set; } public string ProductName { get; set; } = string.Empty; public string BrandName { get; set; } = string.Empty; public string CategoryName { get; set; } = string.Empty; public short ModelYear { get; set; } public decimal ListPrice { get; set; } } 

Notice there's no BrandId, no CategoryId and no Stocks collection. The DTO is a contract with the outside world. The entity is a mirror of the database. They are allowed to be different.

Step 3: Add AutoMapper and configure the mapping

dotnet add package AutoMapper 

Licensing note: AutoMapper moved to a dual license starting with v15. Classroom/educational use and small companies qualify for the free Community license. You register for a key at automapper.io. Without a key the library still works; it just logs a message. You can set the key in code or with the AUTOMAPPER_LICENSE_KEY environment variable.

AutoMapper is convention-based: properties with the same name map automatically (ProductId → ProductId, ModelYear → ModelYear, ...). BrandName and CategoryName live on related entities though, so we tell AutoMapper where to find them.

Mapping/ShopMappingProfile.cs:

using AutoMapper; using PedalShop.Api.DTOs; using PedalShop.Api.Models; namespace PedalShop.Api.Mapping; public class ShopMappingProfile : Profile { public ShopMappingProfile() { CreateMap<Product, BikeProductDto>() .ForMember(dest => dest.BrandName, opt => opt.MapFrom(src => src.Brand.BrandName)) .ForMember(dest => dest.CategoryName, opt => opt.MapFrom(src => src.Category.CategoryName)); } } 

Register the DbContext and AutoMapper in Program.cs:

using Microsoft.EntityFrameworkCore; using PedalShop.Api.Models; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddOpenApi(); builder.Services.AddDbContext<PedalShopContext>(opts => opts.UseSqlServer(builder.Configuration.GetConnectionString("PedalShopDb"))); // Scans this assembly for Profile classes (ShopMappingProfile) builder.Services.AddAutoMapper(cfg => { // cfg.LicenseKey = builder.Configuration["AutoMapper:LicenseKey"]; }, typeof(Program)); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.MapOpenApi(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); 

Step 4: Use the DTO in the product controller

Here's the products controller after the refactor. The routes are the same as before; only the return types changed.

Controllers/ProductsController.cs:

using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PedalShop.Api.DTOs; using PedalShop.Api.Models; namespace PedalShop.Api.Controllers; [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly PedalShopContext _shopDb; private readonly IMapper _objectMapper; public ProductsController(PedalShopContext shopDb, IMapper objectMapper) { _shopDb = shopDb; _objectMapper = objectMapper; } // GET api/Products [HttpGet] public async Task<ActionResult<IEnumerable<BikeProductDto>>> GetAllBikes() { var bikeRows = await _shopDb.Products .Include(b => b.Brand) .Include(b => b.Category) .AsNoTracking() .ToListAsync(); var bikeDtos = _objectMapper.Map<List<BikeProductDto>>(bikeRows); return Ok(bikeDtos); } // GET api/Products/81 [HttpGet("{bikeId:int}")] public async Task<ActionResult<BikeProductDto>> GetBike(int bikeId) { var bikeRow = await _shopDb.Products .Include(b => b.Brand) .Include(b => b.Category) .AsNoTracking() .FirstOrDefaultAsync(b => b.ProductId == bikeId); if (bikeRow is null) { return NotFound(); } return Ok(_objectMapper.Map<BikeProductDto>(bikeRow)); } } 

Why the .Include() calls?

AutoMapper maps whatever is already in memory. If you forget .Include(b => b.Brand), then src.Brand is null and you'll get an empty brandName (or a NullReferenceException, depending on the AutoMapper version).

Bonus: let the database do the projection

AutoMapper can also translate the mapping into the SQL SELECT itself with ProjectTo, which means you skip the .Include() calls and only fetch the six columns you need:

using AutoMapper.QueryableExtensions; var bikeDtos = await _shopDb.Products .ProjectTo<BikeProductDto>(_objectMapper.ConfigurationProvider) .ToListAsync(); 

Either approach is fine for this exercise.

Step 5: Confirm nothing changed for clients

Run the API:

dotnet run 

Note the port in the console output (e.g. http://localhost:5212) and hit the endpoints:

curl http://localhost:5212/api/Products curl http://localhost:5212/api/Products/81 

Or use the .http file in Visual Studio / VS Code:

@PedalShop.Api_HostAddress = http://localhost:5212 GET {{PedalShop.Api_HostAddress}}/api/Products Accept: application/json ###  GET {{PedalShop.Api_HostAddress}}/api/Products/81 Accept: application/json 

You should get exactly the shape shown at the top of the post. Same URLs, same JSON, cleaner code.

Step 6: The BI endpoint

Now for something a client can't easily compute on its own. For a given category, we want:

Field Meaning
productCount How many products are in this category
currentStockCount Total units of this category on hand across all stores
storeCount How many distinct stores have a non-zero quantity of anything in this category

The DTO

DTOs/CategoryStatsDto.cs:

namespace PedalShop.Api.DTOs; public class CategoryStatsDto { public int CategoryId { get; set; } public string CategoryName { get; set; } = string.Empty; public int ProductCount { get; set; } public int CurrentStockCount { get; set; } public int StoreCount { get; set; } } 

The controller

The requirement is strict: route lives at /api/BI, only a GET by id exists for categories, no "get many", no other verbs.

Controllers/BIController.cs:

using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PedalShop.Api.DTOs; using PedalShop.Api.Models; namespace PedalShop.Api.Controllers; [ApiController] [Route("api/BI")] public class BIController : ControllerBase { private readonly PedalShopContext _shopDb; public BIController(PedalShopContext shopDb) { _shopDb = shopDb; } // GET api/BI/Category/4 [HttpGet("Category/{groupId:int}")] public async Task<ActionResult<CategoryStatsDto>> GetCategoryStats(int groupId) { var groupStats = await _shopDb.Categories .Where(grp => grp.CategoryId == groupId) .Select(grp => new CategoryStatsDto { CategoryId = grp.CategoryId, CategoryName = grp.CategoryName, // a) number of products in the category ProductCount = grp.Products.Count(), // c) total units on hand across every store CurrentStockCount = grp.Products .SelectMany(item => item.Stocks) .Sum(inv => inv.Quantity) ?? 0, // b) distinct stores holding a non-zero amount StoreCount = grp.Products .SelectMany(item => item.Stocks) .Where(inv => inv.Quantity > 0) .Select(inv => inv.StoreId) .Distinct() .Count() }) .AsNoTracking() .FirstOrDefaultAsync(); if (groupStats is null) { return NotFound(); } return Ok(groupStats); } } 

How the calculation works

  • grp.Products is the navigation collection from Category to its Product rows.
  • SelectMany(item => item.Stocks) flattens "products → their stock rows" into one long list of stock rows for the whole category. Each stock row is one (store, product, quantity) triple.
  • Sum(inv => inv.Quantity) adds up every quantity. Quantity is int? in the scaffolded model, so the sum is int? too, hence ?? 0.
  • For StoreCount we keep only rows where Quantity > 0, pull out the StoreId, Distinct() it, and count.

Because everything happens inside .Select(...) on an IQueryable, EF Core translates the whole thing into a single SQL query with sub-selects. Nothing gets pulled into memory except the final five numbers.

Why not AutoMapper here? You could write a CreateMap<Category, CategoryStatsDto>() with MapFrom expressions and use ProjectTo. For aggregate/derived values like these, I find a hand-written projection easier to read and debug. Use AutoMapper where it removes boilerplate, not where it hides logic.

Test it

curl http://localhost:5212/api/BI/Category/4 
{ "categoryId": 4, "categoryName": "Cruisers Bicycles", "productCount": 14, "currentStockCount": 306, "storeCount": 3 } 

Try a category that doesn't exist:

curl -i http://localhost:5212/api/BI/Category/999 # HTTP/1.1 404 Not Found 

And confirm there's no "get many":

curl -i http://localhost:5212/api/BI/Category # HTTP/1.1 404 Not Found 

Sanity-check the numbers in SQL

If you want to prove the API is right, run this directly against BikeStores:

DECLARE @cat INT = 4; SELECT (SELECT COUNT(*) FROM production.products WHERE category_id = @cat) AS product_count, (SELECT SUM(s.quantity) FROM production.stocks s JOIN production.products p ON p.product_id = s.product_id WHERE p.category_id = @cat) AS current_stock_count, (SELECT COUNT(DISTINCT s.store_id) FROM production.stocks s JOIN production.products p ON p.product_id = s.product_id WHERE p.category_id = @cat AND s.quantity > 0) AS store_count; 

Final project layout

PedalShop.Api/ ├── Controllers/ │ ├── BIController.cs │ └── ProductsController.cs ├── DTOs/ │ ├── BikeProductDto.cs │ └── CategoryStatsDto.cs ├── Mapping/ │ └── ShopMappingProfile.cs ├── Models/ │ ├── Brand.cs │ ├── Category.cs │ ├── PedalShopContext.cs │ ├── Product.cs │ ├── Stock.cs │ └── Store.cs ├── appsettings.json ├── PedalShop.Api.http └── Program.cs 

Takeaways

  • Entities describe the database. DTOs describe the API contract. Keep them separate and you can change one without breaking the other.
  • AutoMapper removes the boring new Dto { A = x.A, B = x.B, ... } code. Use ForMember when names don't line up, and remember to Include related data (or use ProjectTo).
  • BI endpoints are a great place for DTOs, because the response is computed, not a row from a table.
  • Keep the surface area small: if the spec says "GET by id only," don't add verbs you'll have to secure and maintain later.

Thanks for reading! 🚲