首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Entity Framework Core 懒加载

来源:Sweet-Tang

cnblogs.com/tdfblog/p/entity-framework-lazy-loading.html

众所周知在EF 6 及以前的版本中,是支持懒加载(Lazy Loading)的,可惜在EF Core 并不支持,必须使用Include方法来支持导航属性的数据加载。

不过现在EF Core的开发团队打算恢复对这一功能的支持(目前还未发布,不过可以在Github上面下载进行测试)。

懒加载

懒加载也可以叫做按需加载、延迟加载。可以分两方面来理解,一方面指暂时不需要该数据,不用在当前马上加载,而可以推迟到使用它时再加载;另一方面指不确定是否将会需要该数据,所以暂时请不要加载,待确定需要后再加载它。

懒加载是一种很重要的数据访问特性,可以有效地减少与数据源的交互(注意,这里所提的交互不是指交互次数,而是指交互的数据量),从而提升程序性能。

EF 6 懒加载

我们先来看一看在EF 6中的懒加载的使用方式。

实体定义:

public class Order

{

public int OrderID { get; set; }

public string CustomerID { get; set; }

public DateTime? OrderDate { get; set; }

public virtual ICollection OrderDetails { get; set; }

}

public class OrderDetail

{

public int OrderID { get; set; }

public int ProductID { get; set; }

public decimal UnitPrice { get; set; }

public short Quantity { get; set; }

public float Discount { get; set; }

public virtual Order Order { get; set; }

}

我们在这里定义订单、订单明细实体,它们是一对多关系,通过OrderId字段进行关联。

using (NorthwindContext context = new NorthwindContext()) {

Order order = await context.Orders.SingleAsync(item => item.OrderID == 10253);

Assert.NotNull(order);

Assert.NotNull(order.OrderDetails);

Assert.Equal(3, order.OrderDetails.Count);

}

}

在查询订单号为 10253 的订单后,如果我们需要访问订单的明细,不需要再编写一次数据查询的代码,直接访问导航属性即可,EF会自动帮我们填充属性的值。

懒加载需要注意以下两点:

在配置中启用了懒加载(默认开启);

实体类不能是封闭(sealed)类,导航属性必须是虚(virtual)属性。

在 EF Core 中启用懒加载

目前EF Core发布的最新版本中并不支持懒加载,开发人员必须使用Include方法,才能完成导航属性的加载。

using (NorthwindContext context = new NorthwindContext()) {

Order order = await context.Orders.Include(e => e.OrderDetails).SingleAsync(item => item.OrderID == 10253);

Assert.NotNull(order);

Assert.NotNull(order.OrderDetails);

Assert.Equal(3, order.OrderDetails.Count);

}

大家需要在Github上面下载最新的源代码来测试这一功能aspnet/EntityFrameworkCore:

https://github.com/aspnet/EntityFrameworkCore

启用懒加载:

public class NorthwindContext : DbContext

{

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

var sqlConnectionStringBuilder = new SqlConnectionStringBuilder {

DataSource = "****",

InitialCatalog = "Northwind",

UserID = "sa",

Password = "sa"

};

optionsBuilder.UseSqlServer(sqlConnectionStringBuilder.ConnectionString);

optionsBuilder.UseLazyLoadingProxies();

base.OnConfiguring(optionsBuilder);

}

}

要在通常的应用程序中使用,只需在DbContext的OnConfiguring方法中添加对UseLazyLoadingProxies()扩展方法调用即可。

框架目前是通过Castle.Core框架来生成代理类来实现对导航属性的延迟加载,开发团队打算将该功能做为EF Core的可选安装包。

如果您对该功能感兴趣,可以在Github上面下载源代码进行测试。

Github:https://github.com/aspnet/EntityFrameworkCore

看完本文有收获?请转发分享给更多人

关注「DotNet」,提升.Net技能

淘口令:复制以下红色内容,再打开手淘即可购买

范品社,使用¥极客T恤¥抢先预览(长按复制整段文案,打开手机淘宝即可进入活动内容)

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180124B0AM2600?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券