I needed a way for a new API NET CORE Web API
project to surface data from an existing MySQL instance, EF Core felt like a simple solution. These were the steps I followed. The API was built ontop of net8.0
for reasons of LTS and its what the cool kids are using 😎
- Install nuget packages, for compatibility reasons with the OData packages I needed to use these versions but latest will probably work for you.
1 | EFCore.NamingConventions v8.0.0 |
- Create the domain models adding the relationships, here one
Risk
had manyRiskLines
. Additionally add foreign keys and navigation props between the objects.
1 | namespace Foo.Api.Domain.Models; |
1 | namespace Foo.Api.Domain.Models; |
- Define the database context and pass the options the base object. Configure the table and column mapping, case fixes, name clashes and relationships.
1 | using Microsoft.EntityFrameworkCore; |
- Update appsettings.json to have the connection string, I just love how easy it is to read from appsettings in .Net 💋
1 | "ConnectionStrings": |
- Inject the context into the DI container and configure the options.
1 | var connectionString = builder.Configuration.GetConnectionString("FooConnectionString"); |
- Create the public DTO objects, this often feels like duplication but this ensures you dont leak domain concearns into your public API.
Here you may need to configure values to be nullable.
1 | namespace Foo.Api.Models; |
1 | namespace Foo.Api.Models; |
- Create mappers for Domain to Dto objects:
1 | using Foo.Api.Domain.Models; |
- Finally inject the context and return the values, here the
ProblemDetails
will expose internal details, this was just for testing. In production you would log the exception and raise a ProblemDetails object sensible for your consumers. These endpoints are also a bit wierd because they used with OData annotations not shown here.
1 | public async Task<ActionResult<IEnumerable<RiskDto>>> Get() |
1 | public async Task<ActionResult<RiskDto>> Get([FromRoute] int key) |