Using the new LengthAttribute in .NET 8 with EFCore and Swashbuckle
In .NET 8 Preview 2 and the final release, a new LengthAttribute which is a shorter-hand for using both MinLengthAttribute and MaxLengthAttribute but not a replacement. However, this support did not show up in EFCore 8 and is yet to be added to Swashbuckle.AspNetCore. See this GitHub issue for EFCore, but I could not find any for Swashbuckle.
The model
The model before looked like this:
The model changes to:
Entity Framework Core 8
To make EFCore 8 pickup maximum length from the LengthAttribute, you can override the OnModelCreating(...) method ad iterate through entities and their properties but if you have this nested beyond one level, it does not work. The solution to this is a convention that can be applied to the whole context. In fact, the inbuilt support for MaxLengthAttribute is done via a convention; see the source.
We can use this as the base to build our own convention LengthAttributeConvention:
To register this I use an extension method since there are many other conventions I have:
In the DB Context:
Swashbuckle/Swagger/OpenAPI support
To add this support, we need to create a schema filter by implementing ISchemaFilter. We are guided by two files in the codebase:
Notice that we set MinItems and MaxItems for arrays while we set MinLength and MaxLength for the others. This matches usage for collections (e.g. IList<T>, IEnumerable<T>, etc.) and strings respectively.
Next we register the filter in the options:
That's all, now you will have the same behaviour as when not using MinLengthAttribute and MaxLengthAttribute.
This functionality may be added to the respectively libraries in the future rendering the code here useless.