Entity Framework Tutorial Basics(38):Explicit Loading

本文介绍了如何使用DbContext的Load方法进行显式加载关联实体。即使禁用了懒加载,仍可通过显式调用Load方法来加载相关实体。文章通过具体代码示例展示了如何加载单一导航属性及集合导航属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Explicit Loading with DBContext

Even with lazy loading disabled, it is still possible to lazily load related entities, but it must be done with an explicit call. Use the Load method of DBEntityEntry object to accomplish this.

The following code explicitly loads Standard of particular Student using the Reference() method of DbEntityEntry:

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();
}     

 

If you run the code shown above, you can see that it first loads student but not standard, as shown below:

Entity Framework tutorial 4.3 dbcontext

The load method to get the Standard entity is shown below:

Entity Framework tutorial 4.3 dbcontext

The code shown above will execute two different database queries. The first query gets Student and the second query gets Standard.

Load collection:

Use the Collection() method instead of Reference() method to load collection navigation property. The following example loads the courses of student.

using (var context = new SchoolDBEntities())
{
    context.Configuration.LazyLoadingEnabled = false;
                
    var student = (from s in context.Students
                        where s.StudentName == "Bill"
                        select s).FirstOrDefault<Student>();

    context.Entry(student).Collection(s => s.Courses).Load();
}

 

Note: The Load extension method works just like ToList, except that it avoids the creation of the list altogether.

转载于:https://www.cnblogs.com/purplefox2008/p/5649436.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值