Skip to content

Instantly share code, notes, and snippets.

@DiomedesDominguez
Created August 14, 2020 20:03
Show Gist options
  • Save DiomedesDominguez/7e28e17feb50e0bc9c85f7e01d6d9cd3 to your computer and use it in GitHub Desktop.
Save DiomedesDominguez/7e28e17feb50e0bc9c85f7e01d6d9cd3 to your computer and use it in GitHub Desktop.
Change the default datatype for string
public static void SetDefaultDataType(this ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes().Where(x => x.ClrType.GetCustomAttribute(typeof(TableAttribute)) != null))
{
var entityClass = entity.ClrType;
foreach (var property in entityClass.GetProperties().Where(p => p.PropertyType == typeof(string)
&& p.PropertyType.IsPublic && p.CanWrite
&& !Attribute.IsDefined(p, typeof(ColumnAttribute))
&& !Attribute.IsDefined(p, typeof(NotMappedAttribute))))
{
var maxLength = "max";
if (Attribute.IsDefined(property, typeof(MaxLengthAttribute)))
{
maxLength = (property.GetCustomAttributes(typeof(MaxLengthAttribute), true).First() as MaxLengthAttribute).Length.ToString();
}
else if (Attribute.IsDefined(property, typeof(StringLengthAttribute)))
{
maxLength = (property.GetCustomAttributes(typeof(StringLengthAttribute), true).First() as StringLengthAttribute).MaximumLength.ToString();
}
modelBuilder.Entity(entityClass).Property(property.Name).HasColumnType($"varchar ({maxLength})");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment