3

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)");
ntziolis
  • 10,091
  • 1
  • 34
  • 50

2 Answers2

7
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>();
}
Kim Tranjan
  • 4,521
  • 3
  • 39
  • 38
5
[System.ComponentModel.DataAnnotations.MaxLength]
Kyle
  • 1,172
  • 1
  • 8
  • 23