Created
August 14, 2020 20:03
-
-
Save DiomedesDominguez/7e28e17feb50e0bc9c85f7e01d6d9cd3 to your computer and use it in GitHub Desktop.
Change the default datatype for string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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