EF 导航属性的使用

99封情书 提交于 2020-01-11 22:35:54
//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);
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!