标签 标签 标签
- 一句话的事儿:
加载关联数据的类型
- 预加载 -Eager loading
- 显示加载 -Explicit loading
-
预加载 -Eager loading
第一种写法:DbSet<>
var clubs = context.Clubs
.Include(x => x.League)
.ToList();
:::info
FirstOrDefault()必须是IQuerable()
- Find()不支持Include()
:::
var clubs = context.Clubs
.Where(x => x.Id > 0)
.Include(x => x.League) //俱乐部关联的联赛
.Include(x => x.Players) //俱乐部关联的球员
.ThenInclude(x => x.Resume) //俱乐部关联某个球员,球员关联某个简历
.Include(x => x.Players)
.ThenInclude(x => x.GamePlayers)
.ThenInclude(x => x.Game)
.ToList();
第二种写法:LinQ
var query = context.Clubs
.Where(x => x.Id > 0)
.Select(x => new
{
x.Id,
LeagueName = x.League.Name,
x.Name,
Players = x.Players
.Where(p => p.DateOfBirth > new DateTime(1990, 1, 1))
}).ToList();
:::info DbContext不能识别上述的匿名类,只能追踪它识别的类 :::
显示加载 -Explicit loading
第一种:
var info = context.Clubs.First();
context.Entry(info)
.Collection(x => x.Players)
.Query()
.Where(x=>x.DateOfBirth>new DateTime(1980,12,5))
.Load();
context.Entry(info).Reference(x => x.League).Load();
懒加载 -lazy loading(不建议使用)
最后聊一下多对多的查询
EF Core是实现不了多对多的查询,假如我们查询GamePlayer,然后再DataContext中,我们并没有该表(其实是这个表没有在DbSet中体现),那么可以通过如下方法:
var gamePlayers = context.Set<GamePlayer>()
.Where(x => x.Player.Id > 0)
.ToList();
- 本文作者:GeekPower - Felix Sun
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!