欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

EF 导航属性的使用

程序员文章站 2022-07-13 22:36:51
...
//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);
        }
    }
}
相关标签: C# 知识点