RAD Studio 10.4.1 is now available! Learn more. 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>();
}
}


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

Related posts
C++

What's New in the GetIt Package Manager - June 2020

C++

RAD Studio 10.4 Now Available, Learn More

C++NewsRAD Studio

Open for Business with 10.4! - May 2020 GM Update

C++DelphiNews

Embarcadero Open Source Project Sponsorship

Leave a Reply

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

IN THE ARTICLES