Member-only story

Using the new LengthAttribute in .NET 8 with EFCore and Swashbuckle

Maxwell Weru
3 min readNov 21, 2023

--

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:

public class MyClass
{
[MinLength(5), MaxLength(12)]
public string RegistrationNumber { get; set; }
}

The model changes to:

public class MyClass
{
[Length(5, 12)]
public string RegistrationNumber { get; set; }
}

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:

using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using…

--

--

Maxwell Weru
Maxwell Weru

Written by Maxwell Weru

Learning to live the best life I can

No responses yet