lazy Eager Loading #ef
ctx.Configuration.LazyLoadingEnabled=false;
using (var ctx = new SchoolDBEntities())
{
//Loading students only
IList<Student> studList = ctx.Students.ToList<Student>();
Student std = studList[0];
//Loads Student address for particular Student only (seperate SQL query)
StudentAddress add = std.StudentAddress;
}
using (var context = new SchoolDBEntities())
{
//Disable Lazy loading
context.Configuration.LazyLoadingEnabled = false;
var student = (from s in context.Students
where s.StudentName == "Bill"
select s).FirstOrDefault<Student>();
context.Entry(student).Reference(s => s.Standard).Load();
}
// Loading Method Lazy Loading的意思就是不加在关联数据,ToList过的表就不用延迟加载了,
// 因为已经全部在内存中了ExplicitLoading就是当Lazy Loading关闭了,还是可以再加载关联的数据,
// 不过是需要显示的声明Eager Loading使用Include方法关联预先加载的实体Include(),两表必须含有外键关系,
// 只需要指定键名对应的类属性名即可,不需指定结果字段(即全部映射)。默认搜索某表时,不会顺带查询外键表,
// 直到真正使用时才会再读取数据库查询;若是使用 Include(),则会在读取本表时把指定的外键表信息也读出来。
using (var ctx = new SchoolDBEntities())
{
stud = ctx.Students.Include("Standard")
.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
}
//////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data.Entity;
class Program
{
static void Main(string[] args)
{
using (var ctx = new SchoolDBEntities())
{
stud = ctx.Students.Include(s => s.Standard)
.Where(s => s.StudentName == "Student1")
.FirstOrDefault<Student>();
}
}
}
/////////////////////////////////////////////////////////////////////
using (var ctx = new SchoolDBEntities())
{
stud = ctx.Students.Include(s => s.Standard.Teachers)
.Where(s => s.StudentName == "Student1")
.FirstOrDefault<Student>();
}