ASP.NET 向用户添加集合的核心 - 对象引用未设置为对象的实例

ASP.NET Core adding collection to User - Object reference not set to an instance of an object

我正在尝试为我的用户添加英雄。

用户模型:

public class AppUser : IdentityUser
{
    public ICollection<Hero> Heroes { get; set; }
}

英雄模型:

public class Hero
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Ability { get; set; }

    [Required]
    public string SuitColors { get; set; }
    public double CurrentPower { get; set; }
    public double StartingPower { get; set; }
    public DateTime Created { get; set; } = DateTime.Now;
    public ICollection<PowerUp> PowerUps { get; set; }
    public AppUser AppUser { get; set; }

    [Required]
    public string AppUserId { get; set; }
}

数据上下文:

public class DataContext : IdentityDbContext<AppUser>
{
    public DataContext(DbContextOptions options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<Hero>().HasMany(hero => hero.PowerUps).WithOne(powerUp => powerUp.Hero)
            .OnDelete(DeleteBehavior.Cascade);

        builder.Entity<AppUser>().HasMany(user => user.Heroes).WithOne(hero => hero.AppUser)
            .OnDelete(DeleteBehavior.Cascade);

    }
}

当我尝试向用户添加英雄时出现问题:

    [HttpPost("{create}")]
    public async Task<ActionResult> CreateHero(RegisterHeroDto registerHeroDto)
    {
        var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        var user = await _userRepository.GetUserByIdAsync(userId);

        if (user == null)
        {
            return NotFound();
        }

        var hero = this.BuildHero(registerHeroDto);

        user.Heroes.Add(hero); // here is the error

        return Ok();
    }

    private Hero BuildHero(RegisterHeroDto registerHeroDto)
    {
        var startingPower = registerHeroDto.Ability == "attacker" ? 10 : 5;

        var hero = new Hero
        {
            Name = registerHeroDto.Name,
            Ability = registerHeroDto.Ability,
            SuitColors = registerHeroDto.SuitColors,
            StartingPower = startingPower,
            CurrentPower = startingPower,
            AppUserId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value
        };


        return hero;
    }

错误:

Object reference not set to an instance of an object.
  System.NullReferenceException: Object reference not set to an instance of an object.

有谁知道为什么会出现这种错误?我不确定是什么原因造成的,因此,我不知道如何解决它。 任何人都可以向我解释导致错误的原因以及我应该如何解决它? 谢谢!

始终在创建时初始化 Icollection 或 List,这样我们就不需要忘记稍后对其进行初始化。

public class AppUser : IdentityUser
{
    public AppUser () {
        Heroes = new List<Hero>();
    }
    public ICollection<Hero> Heroes { get; set; }
}

public class Hero
{

    public Hero () {
        PowerUps = new List<PowerUp>();
    }
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Ability { get; set; }

    [Required]
    public string SuitColors { get; set; }
    public double CurrentPower { get; set; }
    public double StartingPower { get; set; }
    public DateTime Created { get; set; } = DateTime.Now;
    public ICollection<PowerUp> PowerUps { get; set; }
    public AppUser AppUser { get; set; }

    [Required]
    public string AppUserId { get; set; }
}