“short”类型必须是引用类型才能在泛型类型中将其用作参数“TTargetEntity”

时间:2016-07-29 11:56:28

标签: c# asp.net entity-framework ef-code-first entity-framework-6

我尝试使用Fluent API添加配置如下:

public class PeriodTypeMappings: EntityTypeConfiguration<PeriodType>
    {
        public PeriodTypeMappings()
        {
            this.HasKey(p => p.PeriodTypeId);
            this.Property(p => p.PeriodTypeName).HasMaxLength(value: 25);
            this.HasRequired(p => p.PeriodTypeName);
            this.HasRequired(p => p.NumberOfPartitions);//compile error
        }
    }

但我得到以下例外:

  

“short”类型必须是引用类型才能将其用作   泛型类型或方法中的参数'TTargetEntity'   'EntityTypeConfiguration.HasRequired(表达式&GT)'

this.HasRequired(p => p.NumberOfPartitions);类型为short的最后一行NumberOfPartitions发生了异常。

为什么会发生这种情况以及如何解决这个问题,我试着说这个字段是必需的。

1 个答案:

答案 0 :(得分:2)

HasRequired 用于映射导航属性。您要找的是 IsRequired 。但是,如果您的属性不可为空,则默认情况下是必需的。您的映射应如下所示:

this.HasKey(p => p.PeriodTypeId);

this.Property(p => p.PeriodTypeName)
    .IsRequired()
    .HasMaxLength(25);

this.Property(p => p.NumberOfPartitions)
    .IsRequired();
相关问题