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); } } } 
6
  • Can you add both classes and how you configured them on the DbContext? Commented Jan 6, 2018 at 19:39
  • Nothing special about it Commented Jan 6, 2018 at 19:42
  • Where's the Foreing Key that links Hero to Guild? You need a GuildId in Hero Commented Jan 6, 2018 at 19:46
  • I dont think so as ef core seems to have figured that out with the migration script, also that would not explain how include works fine when calling all the heroes first Commented Jan 6, 2018 at 19:47
  • 1
    Please read here to enable SQL logging. We'll need to see what SQL is being generated and what's your database Commented Jan 6, 2018 at 19:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.