知道为什么这一行
var guild = _context.Guilds.Include(x => x.Heroes).Single(x => x.Id == 1);
在公会中留下英雄无效,但如果我先这样做
var heroes = _context.Heroes.ToList();
var guild = _context.Guilds.Include(x => x.Heroes).Single(x => x.Id == 1);
那么公会对象上的英雄已被包括在内,现在工作正常吗?
的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);
}
}
}