![developer5 | Embarcadero RAD Studio Delphi C++Builder Blogs](https://i0.wp.com/blogs.embarcadero.com/wp-content/uploads/2020/08/developer5.jpg?resize=1140%2C694&ssl=1)
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>();
}
}
Design. Code. Compile. Deploy.
Start Free Trial Upgrade Today
Free Delphi Community Edition Free C++Builder Community Edition