FirstOrDefaultAsync 返回 System.NullReferenceException [错误来源不明确]

FirstOrDefaultAsync returning System.NullReferenceException [error origin not clear]

我正在努力构建一个 ASP.NET 核心网络 API 并且不断获得 System.NullReferenceException: 'Object reference not set to an instance of an object.' 我的模型工作正常,但突然开始抛出错误。这是我的数据库实体 class:

public class LocationEntity
{
    protected LocationEntity() { }

    [Key]
    public Guid Id { get; set; }

    [Required]
    [MaxLength(200)]
    public string Title { get; set; }

    [Required]
    [MaxLength(200)]
    public string NormalizeTitle { get => this.Title.ToUpper(); set => value = this.Title.ToUpper(); }

    [Required]
    public DateTime DateCreated { get => _dateCreated; set => _dateCreated = value; }

    DateTime _dateCreated = DateTime.UtcNow;
}

然后我有一个区域实体继承自位置:

public class AreaEntity : LocationEntity
{
    public AreaEntity() { }

    [Required]
    public Guid CountryId { get; set; }
    public CountryEntity Country { get; set; }

    [Required]
    public Guid StateId { get; set; }
    public StateEntity State { get; set; }

    [Required]
    public Guid CityId { get; set; }
    public CityEntity City { get; set; }

    [Required]
    public Guid SubCityId { get; set; }
    public SubCityEntity SubCity { get; set; }

    [Required]
    [MaxLength(10)]
    public string Pincode { get; set; }

}

在我的 AddressService.cs 中,我有一个名为 PopulateMasterData 的函数:

AreaEntity area = null;
var country = await _context.tbl_Country.Where(x => x.NormalizeTitle == model.Country.ToUpper()).FirstOrDefaultAsync();

          if (country.IsNull())
              country = (await _context.tbl_Country.AddAsync(new CountryEntity { Title = model.Country })).Entity;

并类似地检查州、城市等,如果字段是唯一的,则创建区域实体。

我在 LocationEntity 的这一步遇到错误 class

[Required]
    [MaxLength(200)]
    public string NormalizeTitle { get => this.Title.ToUpper(); set => value = this.Title.ToUpper();

我不明白这个错误的原因,也不知道是什么没有被初始化。 有人可以解释一下吗?

编辑:国家实体:

 public class CountryEntity: LocationEntity
{
    public CountryEntity() { }
}

this 关键字引用 class 的当前实例。当您实例化 class 并设置 NormalizeTitle 属性 的值时,尚未创建该对象。这就是为什么你会得到 NullReferenceException