(精华)2020年8月19日 数据库设计 导航属性的使用

//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).Reference(c => c.Users).Load();
        foreach (var user in company.Users)//再去查用户
        {
     
            Console.WriteLine(user.Name);
        }
    }
}

你可能感兴趣的:(数据库)