Entity Framework 的懒加载、预先加载、显示加载
1.新建两个实体,一个班级有多个学生
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public Grade Grade { get; set; }
}
public class Grade
{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
2.控制台代码
using (var db = new MyDbContext())
{
db.Database.Log = (sql) => Console.WriteLine(sql);
//懒加载 foreach时才会生成Sql语句,导航属性也是如此
foreach (var item in db.Grade)
{
Console.WriteLine($"班级名称:{item.GradeName}");
foreach (var subItem in item.Students)
{
Console.WriteLine($"学生名称:{subItem.StudentName}");
}
}
//预先加载 foreach时生成查询一个包含导航属性的查询语句,返回一个大实体,foreach students的不再查询数据库
var grades = db.Grade.Include(g => g.Students);
foreach (var item in grades)
{
Console.WriteLine($"班级名称:{item.GradeName}");
foreach (var subItem in item.Students)
{
Console.WriteLine($"学生名称:{subItem.StudentName}");
}
}
//预先加载过滤
db.Configuration.LazyLoadingEnabled = false;
var filterGrades = db.Grade
.Select(g => new
{
g,
Students = g.Students.Where(s => s.StudentId > 0)
})
.AsEnumerable()
.Select(x => x.g);
foreach (var item in filterGrades)
{
Console.WriteLine($"班级名称:{item.GradeName}");
if (item.Students != null)
{
foreach (var subItem in item.Students)
{
Console.WriteLine($"学生名称:{subItem.StudentName}");
}
}
}
//显示加载 可以显示的控制加载的导航属性
db.Configuration.LazyLoadingEnabled = false;
var grade = db.Grade.First();
db.Entry(grade).Collection(c => c.Students).Take(1).Load();
Console.WriteLine($"班级名称:{grade.GradeName}");
foreach (var item in grade.Students)
{
Console.WriteLine($"学生名称:{item.StudentName}");
}
}