【问题标题】:The type 'short' must be a reference type in order to use it as parameter 'TTargetEntity' in the generic type类型“short”必须是引用类型才能将其用作泛型类型中的参数“TTargetEntity”
【发布时间】:2016-07-29 11:56:28
【问题描述】:

我尝试使用 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(Expression>)'

异常发生在最后一行this.HasRequired(p =&gt; p.NumberOfPartitions);,其中NumberOfPartitions 是short 类型。

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多