为什么在使用 Include 时出现“The cast to value type 'System.Int32' failed because the materialized value is null”错误

Why the error 'The cast to value type 'System.Int32' failed because the materialized value is null' when using Include

我首先在代码中有以下 POCO 实体 Entity Framework 6.1.3 应用程序:

public class JobTitle
  {
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int JobTitleId { get; set; }
    public virtual string Description { get; set; }
    public virtual string ShortDescription { get; set; }
    public virtual int? PostId { get; set; }
    [ForeignKey("PostId")]
    public virtual Post Post { get; set; }
  }

实体配置如下:

  public class JobTitleConfiguration : EntityTypeConfiguration<JobTitle>
  {
    public JobTitleConfiguration()
    {
      Property(j => j.PostId).HasColumnName("Post_PostId");
      HasOptional(j => j.Post);
    }
  }

如果有没有关联的 JobTitles Post:

,则以下查询给出空值错误
var list=JobTitles.Include(j=>j.Post).ToList();

我不明白为什么,因为外键可以为空并且在配置中指定为可选。

我怎样才能预先加载 Post 信息,但仍然避免这个错误?

需要检查的几件事:

  • 您的 PostId 属性 在 Post class 中是否也可以为空?
  • 您的数据库中 "JobTitleId" 是否有空值?