Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
News

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>();
}
}

See What's New in 12.2 Athens See What's New in 12.2 Athens Dev Days of Summer 2-24

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES