我读过这个tutorial http://www.entityframeworktutorial.net/EntityFramework5/entity-framework5-introduction.aspx和这个article https://msdn.microsoft.com/en-us/data/jj574232.aspx但我不太明白每种加载类型的用途。
我解释
我有这个 POCO :
public partial class dpc_gestion
{
public dpc_gestion()
{
this.ass_reunion_participant = new HashSet<ass_reunion_participant>();
this.dpc_participant = new HashSet<dpc_participant>();
this.dpc_reunion = new HashSet<dpc_reunion>();
}
public int dpc_id_pk { get; set; }
public Nullable<int> dpc_id_gdp_fk { get; set; }
public Nullable<int> dpc_id_theme { get; set; }
public int dpc_id_animateur_fk { get; set; }
public Nullable<System.DateTime> dpc_date_creation { get; set; }
public Nullable<System.DateTime> dpc_date_fin { get; set; }
public Nullable<System.DateTime> dpc_date_engag_anim { get; set; }
public Nullable<bool> dpc_flg_let_engag_anim { get; set; }
public Nullable<bool> dpc_flg_fsoins_anim { get; set; }
public virtual ICollection<ass_reunion_participant> ass_reunion_participant { get; set; }
public virtual theme_dpc theme_dpc { get; set; }
public virtual gdp_groupe_de_pair gdp_groupe_de_pair { get; set; }
public virtual ICollection<dpc_participant> dpc_participant { get; set; }
public virtual ICollection<dpc_reunion> dpc_reunion { get; set; }
}
我明白了这一点:
-
对于延迟加载:因为加载是惰性的,如果我调用dbsetdpc_gestion
所有导航属性won't被加载。这种类型的加载在性能和响应能力方面是最好的。它默认启用,如果我想重新启用它,我必须设置:
context.Configuration.ProxyCreationEnabled = true;
context.Configuration.LazyLoadingEnabled = true;
-
对于急切的加载它并不懒惰:它在我加载时加载了所有导航属性dpc_gestion
。可以使用以下方式加载导航属性include
方法。要启用此加载类型:
context.Configuration.LazyLoadingEnabled = false;
对于显式加载这就像急切加载,但我们使用Load
方法而不是include
.
所以我想知道:
- 这份小简历是否属实?
- 如果这是真的,那么急切加载和显式加载有什么区别?
- 如果我使用延迟加载我打电话给例如
dpc_gestion.dpc_participant
,导航属性是否加载?否则我会得到异常?
- 是否存在急切加载或显式加载在性能和响应能力方面优于延迟加载的情况?
Thanks
这份小简历是否属实?
Yes.
如果这是真的,那么急切加载和显式加载有什么区别?
预加载是相反的延迟加载 but 显式加载类似于延迟加载, 除了那个:您在代码中显式检索相关数据;当您访问导航属性时,它不会自动发生。您可以通过获取实体的对象状态管理器条目并调用Collection.Load
收集方法或Reference.Load
保存单个实体的属性的方法。
From techblog http://techblog.treenodes.com/index.php/2012/06/26/understanding-lazy-loading-eager-loading-and-explicit-loading-with-entity-framework-implementation/:
急切加载:
预加载是的反面延迟加载的过程是:
与对象一起加载一组特定的相关对象
查询中明确要求的。
显式加载:
显式加载定义为:当查询返回对象时,
相关对象不会同时加载。默认情况下,它们是
除非使用 Load 方法明确请求,否则不会加载
导航属性。
And:
例如,如果我使用延迟加载并且我调用dpc_gestion.dpc_participant
,导航属性是否加载?否则我会得到异常?
您不会遇到任何异常,并且导航属性应该加载。
是否存在急切加载或显式加载更好的情况
在性能和响应能力方面比延迟加载更好吗?
预加载当您需要主表的所有检索行的相关数据时,通常会更有效。而且当关系不是太多的时候,急切加载将是减少服务器上进一步查询的好习惯。但是当您知道您不会立即需要房产时延迟加载也许是一个不错的选择。在您的数据库上下文将被释放并且延迟加载无法再发生的情况下,急切加载也是一个不错的选择。例如,考虑以下内容:
public List<Auction> GetAuctions()
{
using (DataContext db = new DataContext())
{
return db.Auctions.ToList();
}
}
调用此方法后,您无法延迟加载相关实体,因为db
被处置,所以急切加载这里会是一个更好的选择。
还有一点需要注意的是:延迟加载会产生几个SQL请求预加载通过一个请求加载数据。预加载也是解决问题的一个不错的选择n+1选择问题在 ORM 中。
看看这个帖子:什么是n+1选择问题? https://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)