c#-代码优先迁移中的固定长度字符串列
作者:互联网
我正在使用Code First Migrations创建Entity Framework 6模型,并且我希望结果数据库中的列是固定长度而不是可变长度.此外,我想以与DBMS无关的方式执行此操作.
ConventionPrimitivePropertyConfiguration.IsFixedLength方法似乎是为此目的而构建的.我找不到使用它的现有属性,因此我自己创建了一个属性,如下所示:
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Data.Entity.ModelConfiguration.Conventions;
class FixedLengthAttribute : Attribute { }
class FixedLengthAttributeConvention
: PrimitivePropertyAttributeConfigurationConvention<FixedLengthAttribute>
{
public override void Apply(ConventionPrimitivePropertyConfiguration configuration,
FixedLengthAttribute attribute)
{
configuration.IsFixedLength();
}
}
class MyModel : DbContext
{
internal virtual DbSet<MyEntity> MyEntities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new FixedLengthAttributeConvention());
}
}
class MyEntity
{
[Key, FixedLength, StringLength(10)]
public string MyStringProperty { get; set; }
}
但是,使用此代码运行Add-Migration时,在结果迁移文件中定义该数据库列的行(MyStringProperty = c.String(nullable:false,maxLength:10))没有说明固定长度.当我在数据库上运行此迁移时,我得到了NVARCHAR列.
我在这里做错了什么?
解决方法:
StringLength属性似乎覆盖了FixedLength属性.一种解决方法是将length属性添加到FixedLength属性中,然后自行设置HasMaxLength
class FixedLengthAttribute : Attribute
{
public int Length { get; set; }
}
public override void Apply(ConventionPrimitivePropertyConfiguration configuration,
FixedLengthAttribute attribute)
{
configuration.IsFixedLength();
configuration.HasMaxLength(attribute.Length);
}
class MyEntity
{
[Key, FixedLength(Length=10)]
public string MyStringProperty { get; set; }
}
标签:ef-migrations,c,entity-framework 来源: https://codeday.me/bug/20191028/1948780.html