0

Any idea why this line

var guild = _context.Guilds.Include(x => x.Heroes).Single(x => x.Id == 1);

Will leave heroes null on the guild but if I do this first

var heroes = _context.Heroes.ToList();
var guild = _context.Guilds.Include(x => x.Heroes).Single(x => x.Id == 1);

Then heroes on the guild object has been included and now works fine?

DbContext

public class TestContext : DbContext
{
    public TestContext(DbContextOptions options) : base(options)
    { }

    public DbSet<Guild> Guilds { get; set; }
    public DbSet<Hero> Heroes { get; set; }
}

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

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string AvatarId { get; set; }
}

public class Guild : IEntity
{
    public int Id { get; set; }
    public string Name { get;  set; }
    public string UserId { get; set; }
    public List<Hero> Heroes { get; set; }

    public void AddHeroes(IEnumerable<Hero> heroes)
    {
        foreach (var hero in heroes)
        {
            Heroes.Add(hero);
        }
    }
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Luke
  • 59
  • 1
  • 6

0 Answers0