EntityFramework CodeFirst忽略MaxLength

时间:2016-03-29 22:30:34

标签: c# sql-server wpf entity-framework sql-server-ce

我正在使用SQL Server Compact。对于每个表,我有一个包含MaxLength属性的配置。

我运行Add-Migration并正确生成带有maxlength的create列字符串,但是当我运行Update-Database时,正在使用NVARCHAR(MAX)创建列

public class Test{
    public string TestField { get; set; }
}

public class TestConfiguration : EntityTypeConfiguration<Test>
    {
        public TestConfiguration()
        {

            Property(o => o.TestField)
                .HasMaxLength(100);


        }
    }

我的数据库上下文类:

public class PlutoContext : DbContext
{
    public PlutoContext()
        : base("name=PlutoContext")
    {
        this.Configuration.LazyLoadingEnabled = false;
        Database.SetInitializer<PlutoContext>(null);
    }

    public virtual DbSet<Test> Tests { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new TestConfiguration());
    }

生成的迁移

public partial class AddTest : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Test",
            c => new
                {
                   Test = c.String(nullable: false, maxLength: 100),
    }

}

为什么Framework不尊重MaxLength属性?谢谢!

1 个答案:

答案 0 :(得分:-1)

请尝试在OnModelCreating上下文部分中添加类似下面一行的内容:

modelBuilder.Configurations.Add(new TestConfiguration());