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

I am working on building an ASP.NET Core Web API and am continuously getting System.NullReferenceException: 'Object reference not set to an instance of an object.' My model was working fine and it suddenly started throwing an error. Here is my DB entity 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类中遇到了错误

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

我不知道此错误的原因以及尚未初始化的情况。 有人可以解释吗?

评论
  • nerror
    nerror 回复

    The this keyword refers to the current instance of the class. When you are instantiating the class and setting the value, the object is not yet created. That's why you're getting a NullReferenceException