ASP.NET Core 10 Web API CRUD Operations Using Entity Framework Core and SQL Server – Complete Guide (2026)
A product API is a useful first database-backed project: create an item, look it up, change its price, and remove it. The important part is making those operations predictable—validating requests, saving changes asynchronously, and returning the right HTTP status.
This guide builds ASP.NET Core 10 Web API CRUD operations using Entity Framework Core and SQL Server. You will create a controller-based inventory API, generate a SQL Server database with migrations, and test every endpoint in Postman.
How do you build CRUD operations in ASP.NET Core 10?
Create an entity and DbContext, install the EF Core SQL Server provider, register the context with dependency injection, and map controller actions to GET, POST, PUT, and DELETE. Use request DTOs for validation, await database operations, and apply migrations to create the schema.
Scope: this is a local learning application with no authentication. It demonstrates complete CRUD wiring, not a production inventory system. Add authorization, operational controls, and a concurrency strategy before exposing write endpoints publicly.
What ASP.NET Core, EF Core, and SQL Server each do
- ASP.NET Core 10 Web API handles HTTP routing, JSON binding, controller validation, and responses.
- Entity Framework Core 10 maps C# entities to database tables, translates LINQ queries, and tracks changes.
- SQL Server persists the data and executes the database commands.
CRUD means Create, Read, Update, and Delete. In this guide, POST creates, GET reads, PUT replaces the editable product fields, and DELETE removes a product. EF Core is the data-access layer; it does not replace API validation, access control, or business rules.
Prerequisites and Visual Studio setup
- Install the .NET 10 SDK. A runtime-only installation cannot build the project.
- For the Windows IDE workflow, use Visual Studio 2026 version 18.0 or later with the ASP.NET and web development workload. Check Microsoft's SDK and Visual Studio compatibility guidance.
- Install SQL Server 2022 Developer/Express, or SQL Server Express LocalDB for the exact Windows connection string below. Use Developer edition only where its license permits.
- Have SQL Server Management Studio for inspecting the database, plus Postman for API tests.
In Visual Studio, create an ASP.NET Core Empty project named InventoryApi, select .NET 10, and enable HTTPS. We add controller support explicitly, keeping the setup identical to the CLI version. If you use an API template instead, remove generated samples and reconcile its Program.cs with the complete file below.
The CLI workflow is reproducible in Visual Studio's terminal or PowerShell. The LocalDB configuration is Windows-specific; for another operating system, use a reachable SQL Server instance and an appropriate protected connection string.
Step 1: Create the project and install NuGet packages
SqlServer supplies the database provider. Design is needed by migrations tooling. dotnet-ef is a CLI tool installed locally through the tool manifest, not another runtime dependency. Keep the provider, design package, and tool on compatible 10.0 releases; inspect the resolved versions and align package patch versions. A wildcard selects an available patch at installation time, while the saved project and tool manifest record the selected versions.
Using the empty template avoids an implicit Swagger dependency. This guide tests with Postman and does not assume a /swagger page exists.
Step 2: Configure the SQL Server connection securely
For Windows LocalDB, run:
The connection uses Windows integrated authentication, so no SQL password is embedded in the example. User Secrets keeps configuration outside the project, but does not encrypt it and is only for development. The Development environment ensures the default host loads those secrets during migrations and local execution.
Local certificate exception: TrustServerCertificate=True bypasses server certificate verification for this local exercise. Do not copy that setting into production. Use a certificate trusted by the application host, encryption, and certificate verification for a deployed SQL Server connection. Manage production secrets through your host's protected configuration or a secret manager. The environment-variable form of this setting is ConnectionStrings__InventoryDb.
A full SQL Server instance needs its own server name, authentication choice, permissions, and certificate setup. A runtime account should have only the access it needs; the account applying migrations may need broader schema permissions.
Step 3: Add the product entity
Create the Models folder and add Product.cs:
Id is the database-generated identifier. The input contract will not expose it as an editable field. Price uses decimal rather than a floating-point type for this example's two-decimal currency amounts.
Step 4: Add request validation and a response DTO
Create Contracts/ProductContracts.cs:
Nullable numeric properties make omitted price and stock values fail Required validation instead of silently becoming zero. The price validator rejects amounts with more than two decimal places rather than relying on database rounding. This example allows stock zero, rejects negative stock, and requires a nonempty name of at most 100 characters.
The controller's ApiController attribute returns HTTP 400 for invalid model state before the action executes. Request DTOs also limit overposting: the server assigns the product ID and explicitly copies only the fields callers may change. This is controller model validation; it does not rely on Minimal API validation registration. See Microsoft's controller validation documentation.
Step 5: Create the DbContext and SQL mapping
Create Data/AppDbContext.cs:
The context maps Products to dbo.Products under SQL Server's default schema. Name is required and bounded, and Price maps to decimal(18,2). Input validation still matters: schema precision is storage configuration, not a friendly validation response.
The provider setup follows Microsoft's SQL Server provider guidance. AddDbContext registers a scoped context by default. Do not turn it into a singleton or run parallel operations against the same context instance.
Step 6: Register controllers and EF Core in Program.cs
GetConnectionString reads ConnectionStrings:InventoryDb. A missing value fails startup rather than letting the app run with an unintended database. AddControllers registers controller services, and MapControllers exposes attribute-routed actions.
AddProblemDetails and UseExceptionHandler provide a generic error response path. Do not return connection strings, raw SQL exceptions, or stack traces to API callers. This guide applies migrations explicitly with the CLI rather than calling EnsureCreated or silently changing the schema on every app startup.
Step 7: Implement GET, POST, PUT, and DELETE
Create Controllers/ProductsController.cs:
The list query is bounded to 100 items and ordered by the unique Id. It uses keyset-style pagination: request the next batch with afterId set to the last ID received. A short or empty page marks the end of the current results; pages are not a frozen snapshot of a changing database.
Read actions project directly to response DTOs. AsNoTracking also makes the read intent explicit, although this scalar-only projection does not materialize tracked Product entities. Write actions load a tracked entity, assign permitted properties, and await SaveChangesAsync. Cancellation tokens flow to database operations; cancellation remains provider-dependent and is not a transaction rollback guarantee.
The concurrency catch handles affected-row conflicts such as a record disappearing between load and save. This model has no rowversion concurrency token: it does not detect every overlapping edit, and ordinary concurrent updates can overwrite one another. For production conflict detection, add and round-trip a concurrency value or ETag and follow Microsoft's concurrency guidance.
Step 8: Generate migrations and create the SQL Server database
Run from the directory containing InventoryApi.csproj:
InitialCreate generates migration files and a model snapshot from the entity mapping. Inspect the generated files before applying them. Database update creates InventoryApiDb when it does not exist, provided the configured account has permission, and creates the Products and migration-history tables. It does not install or start SQL Server.
Open SSMS and connect to (localdb)\MSSQLLocalDB using Windows authentication. Refresh Databases, expand InventoryApiDb, and verify the tables. If you use a full SQL Server instance, connect to that configured instance instead.
The product query is empty before the first POST. Keep migration files in source control. Use reviewed migration scripts or an appropriate deployment workflow for production; database creation rights should not automatically be granted to the runtime app account. Do not mix EnsureCreated with this migrations workflow. See EF Core's migrations overview.
Step 9: Start the API over local HTTPS
Trust the development certificate only on your own machine. If port 7082 is occupied, change the port and the Postman URLs together. Do not disable certificate validation as a general solution to certificate errors.
Step 10: Test the CRUD endpoints in Postman
Use https://localhost:7082 as the base URL. For POST and PUT, select Body → raw → JSON and send Content-Type: application/json.
Create a product with POST
Expect HTTP 201 Created, a Location header pointing to the new resource, and a body shaped like this. The ID is illustrative; use the actual returned ID in later requests.
Read one product or a bounded list with GET
Get-by-ID returns 200 with a product or 404 if absent. The list endpoint returns 200 with a JSON array, including an empty array when there are no matching products. To retrieve a subsequent batch, replace afterId with the last returned product ID.
Update the product with PUT
Expect 204 No Content, then GET the resource to verify the new price and stock. This PUT requires all three editable fields; it is not a PATCH operation. The server does not create an item when the requested ID is absent: it returns 404.
Remove the product with DELETE
Expect 204 for a successful removal. Repeat GET for that ID and expect 404. Repeating DELETE also returns 404 under this API contract.
Check invalid input
Expect 400 with validation details. Also try omitting price, sending a three-decimal price, and requesting pageSize=1000. All should be rejected. Malformed JSON can fail during binding rather than action execution.
| Operation | Success | Common failure |
|---|---|---|
| GET list | 200 with array | 400 for invalid pagination |
| GET by ID | 200 with object | 404 if absent |
| POST | 201 plus Location | 400 for invalid input |
| PUT | 204, empty body | 404, 400, or detected concurrency conflict 409 |
| DELETE | 204, empty body | 404 or detected concurrency conflict 409 |
Verification note: the implementation patterns were checked against official Microsoft documentation on November 3, 2026. This authoring environment has neither the .NET SDK nor SQL Server, so the complete project has not been compiled or database-tested here. Responses above describe expected behavior, not captured execution results.
Troubleshooting EF Core and SQL Server
- dotnet-ef is unavailable: run the commands inside the tool-manifest directory. On a fresh checkout, restore the local tools with dotnet tool restore.
- Unable to create the DbContext: build first, check the startup project, and ensure Development loads the connection-string secret.
- SQL Server cannot be reached: verify the instance is installed and running. LocalDB and SQL Express use different server names.
- Login or permission failure: confirm the Windows account or configured SQL identity can access the selected instance and has migration permissions where required.
- Invalid object name Products: apply migrations to the same database the app uses; check SSMS and configuration overrides.
- Certificate trust errors: fix the certificate trust and server-name configuration. The local TrustServerCertificate exception is not a production fix.
- 400 before a breakpoint: ApiController can reject an invalid request before the action runs. Inspect validation details and the JSON content type.
- Decimal precision warning: verify the Price mapping and add a migration if the schema changed.
For broader debugger issues, our Visual Studio breakpoint troubleshooting guide can help. For inspecting your database's structure, see finding tables that contain a specified column in SQL Server.
Performance and deployment tips
- Keep list queries bounded and ordered. Avoid loading an entire product catalog for every request.
- Select only the response fields you need and inspect generated SQL or execution plans when performance becomes a problem.
- Await each database call. A DbContext is not thread-safe; Parallel.ForEach over one context is not a safe shortcut.
- Add indexes for measured query patterns instead of indexing every column. This sample's primary key supports its Id-based access pattern.
- Use async operations to avoid blocking during I/O; async alone does not make an inefficient SQL query faster.
- Add authentication and authorization before exposing writes. Keep production database credentials and schema deployment privileges separate.
Microsoft's efficient-querying guide and pagination guide explain the tradeoffs behind these choices.
Frequently asked questions
Do I need a repository layer for EF Core CRUD?
Not for this small example. The controller uses a scoped DbContext directly. Introduce an application service or repository when it provides a useful boundary for business rules, testing, or multiple data sources, rather than adding one solely to wrap each EF method.
Does dotnet ef database update install SQL Server?
No. SQL Server must already be available. The command connects to the configured instance and applies migrations, creating the target database when permissions allow.
Why use DTOs instead of accepting Product directly?
A DTO defines the permitted request fields and validation rules independently of the persistence entity. In this API, callers cannot assign an ID through the write contract.
Why does PUT return 204 instead of updated JSON?
This API returns an empty success response after saving an update. A subsequent GET retrieves the resource. Returning 200 with a representation is another valid contract, but clients must follow the contract the API actually implements.
Can I use SQL authentication instead of Windows authentication?
Yes, with the appropriate connection string and server configuration. Keep credentials in protected configuration, use a least-privilege account, and retain encryption and certificate verification. Do not commit a connection string containing a real password.
Can I add Swagger later?
Yes. OpenAPI describes the API; an interactive documentation UI is a separate choice. This project deliberately uses Postman, so installing the packages above does not create a Swagger UI automatically.
Conclusion
You now have the source for a controller-based ASP.NET Core 10 CRUD API with EF Core and SQL Server: an entity, validated DTOs, a scoped DbContext, dependency injection, migrations, and async endpoints.
Build it locally, create the database, and verify the full lifecycle—POST, GET, PUT, GET, DELETE, then a final 404. Before deploying, add access control, a deliberate concurrency strategy, and a reviewed database migration process.
Comments
Post a Comment