我正在为列创建表设置Maxlength = 5,并使用length = 1创建它

时间:2016-02-05 02:41:28

标签: entity-framework entity-framework-core asp.net-core-1.0

我创建了下表(通过在EF7中使用DNX命令,现在是EF Core)

[Table("FishGrade")]
public partial class FishGrade
{
    public FishGrade()
    {
        FishPrices = new HashSet<FishPrice>();
    }

    [HiddenInput]
    [Column("FishGradeId")]
    public int Id { get; set; }

    [Column("GradeCode")]
    [MaxLength(5), Required]
    public string Code { get; set; }

    [Column("GradeName")]
    public string Name { get; set; }

    public string IsActive { get; set; }

    public virtual ICollection<FishPrice> FishPrices { get; set; }
}

但是当创建表时,Code列(名为= GradeCode的列)将创建为1个字符的长列。

我在OnModelCreating方法

中也有以下内容
 modelBuilder.Entity<FishGrade>(entity =>
        {
            entity.Property(e => e.Code)
                .HasColumnType("char");

            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(50);

            entity.Property(e => e.IsActive)
                .HasMaxLength(1)
                .HasColumnType("char");
        });

为什么会这样?如何使用length = 5创建列?

1 个答案:

答案 0 :(得分:0)

You can define your model in three ways:

  • conventions
  • attributes
  • fluent API

Conventions are applied first, then attributes, and finally the fluent API in your model builder. Your model builder is resetting the attribute configuration.

You should try to simplify your model configuration and use always the same method.

NOTE: take into account that, if you use something like MVC client side validation, it only understands the configuration made via attributes. In all other regards it doesn't mind how you configure your EF model.