Question

Is there a way to create a custom attribute that will make EF CodeFirst use nvarchar(max) as datatype when assigned to a property of a poco class? I know this is possible via fluent api, but we would like to have all definitions within one place and thats the metadata class.

Fluent API:

modelBuilder.Entity<Event>().Property(p => p.TicketText).HasColumnType("nvarchar(max)");
Was it helpful?

Solution

public class NVarcharMaxAttribute : Attribute { }

public class NVarcharMaxAttributeConvention : AttributeConfigurationConvention<PropertyInfo, StringPropertyConfiguration, NVarcharMaxAttribute> {
    public override void Apply(PropertyInfo memberInfo, StringPropertyConfiguration configuration, NVarcharMaxAttribute attribute) {
        configuration.ColumnType = "nvarchar(max)";
    }
}

protected override void OnModelCreating(ModelBuilder modelBuilder) {
    modelBuilder.Conventions.Add<NVarcharMaxAttributeConvention>();
}

OTHER TIPS

[System.ComponentModel.DataAnnotations.MaxLength]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top