标签 标签 标签

  • 一句话的事儿:

加载关联数据的类型

  • 预加载 -Eager loading
  • 显示加载 -Explicit loading
  • 懒加载 -lazy loading

    预加载 -Eager loading

    第一种写法:DbSet<>

    1. var clubs = context.Clubs
    2. .Include(x => x.League)
    3. .ToList();

    image.png :::info

  • FirstOrDefault()必须是IQuerable()

  • Find()不支持Include()
    :::
  1. var clubs = context.Clubs
  2. .Where(x => x.Id > 0)
  3. .Include(x => x.League) //俱乐部关联的联赛
  4. .Include(x => x.Players) //俱乐部关联的球员
  5. .ThenInclude(x => x.Resume) //俱乐部关联某个球员,球员关联某个简历
  6. .Include(x => x.Players)
  7. .ThenInclude(x => x.GamePlayers)
  8. .ThenInclude(x => x.Game)
  9. .ToList();

image.png

第二种写法:LinQ

  1. var query = context.Clubs
  2. .Where(x => x.Id > 0)
  3. .Select(x => new
  4. {
  5. x.Id,
  6. LeagueName = x.League.Name,
  7. x.Name,
  8. Players = x.Players
  9. .Where(p => p.DateOfBirth > new DateTime(1990, 1, 1))
  10. }).ToList();

image.png :::info DbContext不能识别上述的匿名类,只能追踪它识别的类 :::

显示加载 -Explicit loading

第一种:

  1. var info = context.Clubs.First();
  2. context.Entry(info)
  3. .Collection(x => x.Players)
  4. .Query()
  5. .Where(x=>x.DateOfBirth>new DateTime(1980,12,5))
  6. .Load();
  7. context.Entry(info).Reference(x => x.League).Load();

image.png

懒加载 -lazy loading(不建议使用)

最后聊一下多对多的查询

EF Core是实现不了多对多的查询,假如我们查询GamePlayer,然后再DataContext中,我们并没有该表(其实是这个表没有在DbSet中体现),那么可以通过如下方法:

  1. var gamePlayers = context.Set<GamePlayer>()
  2. .Where(x => x.Player.Id > 0)
  3. .ToList();

image.png


  • 本文作者:GeekPower - Felix Sun
  • 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!