Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

Adding a [FixedLength] Attribute in Code-First Entity Framework

Author: Craig Stuntz

In Code First Entity Framework models, you can define the length of a string field with StringLengthAttribute, but you have to write code in OnModelCreating to indicate a CHAR/NCHAR fixed length field:

public class MyEntity
{
[Key]
public int Id { get; set; }

[StringLength(2)]
public string FixedLengthColumn { get; set; }
}

public partial class MyContext : DbContext
{
public virtual DbSet MyEntities { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null) throw new ArgumentNullException("modelBuilder");

modelBuilder.Entity()
.Property(e => e.FixedLengthColumn)
.IsFixedLength();
}
}

I find it a bit confusing to split configuration like this, especially with a real model containing lots of fields and not this trivial example. Fortunately, you can fix it! Add these:

/// <summary>
/// Used to mark entity properties that are fixed length strings (CHAR(n) DB fields).
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class FixedLengthAttribute : Attribute {}

public class FixedLengthAttributeConvention : PrimitivePropertyAttributeConfigurationConvention
{
public override void Apply(ConventionPrimitivePropertyConfiguration configuration, FixedLengthAttribute attribute)
{
configuration.IsFixedLength();
}
}

And change the model configuration to:

public class MyEntity
{
[Key]
public int Id { get; set; }

[StringLength(2),
FixedLength]
public string FixedLengthColumn { get; set; }
}

public partial class MyContext : DbContext
{
public virtual DbSet MyEntities { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null) throw new ArgumentNullException("modelBuilder");

modelBuilder.Conventions.Add<FixedLengthAttributeConvention>();
}
}

Exit mobile version