Workaround for compile-time constant requirement in ASP.NET Core DataAnnotations

45 Views Asked by At

I have various config values defined in the database or appsettings. But those cannot be used in DataAnnotation attributes (which require compile-time constants), so everything is duplicated in a Constants class too.

For example:

[StringLength(Constants.NAME_MAX_LENGTH, ErrorMessage = "...")]
public string Name { get; set; }

One can use localisation to get the error message at runtime (from appsettings, database, etc.) and thus skirt the compile-time constant limitation, but as far as I can tell one cannot use the same approach for the min/max properties too (is that correct?)

Is there some roundabout way I can do something similar for the MinimumLength and MaximumLength properties, so that they can be read dynamically at runtime?

0

There are 0 best solutions below