Skip to content

Instantly share code, notes, and snippets.

@AlexanderBaggett
Created April 24, 2025 14:42
Show Gist options
  • Save AlexanderBaggett/fbc11fc9cdbece219d800035a40ea5c3 to your computer and use it in GitHub Desktop.
Save AlexanderBaggett/fbc11fc9cdbece219d800035a40ea5c3 to your computer and use it in GitHub Desktop.
Inherit Max Length from Interfaces
protected void SetUpMaxLengthViaInterfaces(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var clrType = entityType.ClrType;
var interfaces = clrType.GetInterfaces();
foreach (var interfaceType in interfaces)
{
var interfaceProperties = interfaceType.GetProperties();
foreach (var interfaceProperty in interfaceProperties)
{
var maxLengthAttribute = interfaceProperty.GetCustomAttribute<MaxLengthAttribute>();
if (maxLengthAttribute != null)
{
var entityProperty = clrType.GetProperty(interfaceProperty.Name);
if (entityProperty != null)
{
modelBuilder.Entity(clrType)
.Property(entityProperty.Name)
.HasMaxLength(maxLengthAttribute.Length);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment