EntityFramework 学习 一 Lazy Loading

延迟加载:延迟加载相关的数据

 1 using (var ctx = new SchoolDBEntities())
 2     {
 3         //Loading students only
 4         IList<Student> studList = ctx.Students.ToList<Student>();
 5 
 6         Student std = studList[0];
 7 
 8         //Loads Student address for particular Student only (seperate SQL query)
 9         StudentAddress add = std.StudentAddress;
10     }
11     

 

首先查询Student表

SELECT 
[Extent1].[StudentID] AS [StudentID], 
[Extent1].[StudentName] AS [StudentName], 
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1]
        

 

再查询StudentAddress表

exec sp_executesql N'SELECT 
[Extent1].[StudentID] AS [StudentID], 
[Extent1].[Address1] AS [Address1], 
[Extent1].[Address2] AS [Address2], 
[Extent1].[City] AS [City], 
[Extent1].[State] AS [State]
FROM [dbo].[StudentAddress] AS [Extent1]
WHERE [Extent1].[StudentID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1

 

 

可以为指定的属性或整个上下文关闭延迟加载的功能,关闭属性的延迟加载功能就是不要设置属性为virtual

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
    
public partial class SchoolDBEntities : DbContext
{
    public SchoolDBEntities(): base("name=SchoolDBEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
}
  

 

 延迟加载的规则:

1.context.Configuration.ProxyCreationEnabled必须为true

2.context.Configuration.LazyLoadingEnabled必须为true

3.导航属性必须定义为public virtual

 

转载于:https://www.cnblogs.com/lanpingwang/p/6623068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值