本文介绍了实体框架中的延迟加载、延迟加载和急切加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这3种加载方式有什么区别?有人可以用一个例子来解释吗?不同的在线资源使用不同的定义,造成不必要的混乱.

What are the differences between these 3 types of loading? Can someone explain with an example? Different resources online use different definitions causing more confusion than necessary.

推荐答案

延迟加载和延迟是同义词(AFAIK,如果我错了,请纠正我).最大的区别在于 Eager 和 Lazy 之间.Eager 会预先发生,Lazy 只会在需要时"发生并且执行会发生在 DB 级别——让我们以一个简单的 JOIN 语句为例

Lazy loading and Deferred are pretty synonymous (AFAIK, please correct me if I'm wrong). The big difference is between Eager and Lazy. Eager will happen up front, Lazy happens only "as needed" and execution will happen at the DB level- let's take a simple JOIN statement as an example

var people = (from p in people SELECT p).ToList();
var jobs = (from j in jobs SELECT j).ToList();

var peopleAndJobs = (from p in people JOIN j on j.personId equals p.personId SELECT p).ToList()

这是一个预先加载的例子.我们正在招募所有人,所有工作,并且我们正在加入记忆.不是很聪明(通常).这是 Lazy-style 的样子.

This is an example of eager loading. We are getting ALL people, ALL jobs, and we are doing the join in memory. Not very smart (usually). Here is what it looks like Lazy-style.

var people = (from p in people SELECT p);
var jobs = (from j in jobs SELECT j);

var peopleAndJobs = (from p in people JOIN j on j.personId equals p.personId SELECT p).ToList()

这样做是为人员和工作创建一个 IQueryable(IQueryable 是惰性的),并且连接发生在数据库中.这可以节省网络活动,并且通常实际上更快,因为数据库经过优化以执行连接等操作.

What this is doing is creating an IQueryable for both people and job (IQueryable is lazy), and the join is happening in the DB. This saves network activity, and is usually actually faster, since the DB is optimized to do joins and such.

除非我们明确说我需要这些数据!"(通过 ToListing 它,遍历它等)它很懒惰.还有一些怪癖,但这应该是一本不错的入门书.

Unless we explicitly say "I need that data!" (by ToListing it, iterating through it, etc) it's lazy. There are some more quirks but this should be a decent primer.

这篇关于实体框架中的延迟加载、延迟加载和急切加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:30