//1 默认情况下,导航属性是延迟查询;
//条件是virtaul属性+默认配置
using (JDDbContext dbContext = new JDDbContext())
{
var companyList = dbContext.Set<Company>().Where(c => c.Id < 20);
foreach (var company in companyList)//只差company
{
Console.WriteLine(company.Name);
foreach (var user in company.Users)//再去查用户
{
Console.WriteLine(user.Name);
}
}
}
//2 关闭延迟加载,子表数据就没了
using (JDDbContext dbContext = new JDDbContext())
{
dbContext.Configuration.LazyLoadingEnabled = false;//关闭延迟查询
var companyList = dbContext.Set<Company>().Where(c => c.Id < 20);
foreach (var company in companyList)//只差company
{
Console.WriteLine(company.Name);
foreach (var user in company.Users)//再去查用户
{
Console.WriteLine(user.Name);
}
}
}
//3 预先加载 Include 查询主表时就把子表数据一次性查出来
//其实自己join也可以的
using (JDDbContext dbContext = new JDDbContext())
{
dbContext.Configuration.LazyLoadingEnabled = false;//是否关闭无所谓
var companyList = dbContext.Set<Company>().Include("Users").Where(c => c.Id < 20);
foreach (var company in companyList)//只差company
{
Console.WriteLine(company.Name);
foreach (var user in company.Users)//再去查用户
{
Console.WriteLine(user.Name);
}
}
}
////4 关闭延迟查询后,如果需要子表数据,可以显示加载
using (JDDbContext dbContext = new JDDbContext())
{
dbContext.Configuration.LazyLoadingEnabled = false;//关闭延迟查询
var companyList = dbContext.Set<Company>().Where(c => c.Id < 20);
foreach (var company in companyList)//只查company
{
Console.WriteLine(company.Name);
dbContext.Entry<Company>(company).Collection(c => c.Users).Load();
//dbContext.Entry<Company>(company).Reference(c => c.Users).Load();
foreach (var user in company.Users)//再去查用户
{
Console.WriteLine(user.Name);
}
}
}
来源:CSDN
作者:福建小徐
链接:https://blog.csdn.net/weixin_41181778/article/details/103940858