//条件是virtaul属性+默认配置using(JDDbContext dbContext =newJDDbContext()){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);}}}
二、关闭延迟加载,子表数据就没了
using(JDDbContext dbContext =newJDDbContext()){
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);}}}
三、预先加载 Include 查询主表时就把子表数据一次性查出来(其实自己join也可以的)
using(JDDbContext dbContext =newJDDbContext()){
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);}}}
四、关闭延迟查询后,如果需要子表数据,可以显示加载
using(JDDbContext dbContext =newJDDbContext()){
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);}}}