实体框架中的Lazy和Eager加载在两者中使用.Include()时会得到相同的结果吗?(Lazy and Eager Loading in Entity Framework gives same

编程入门 行业动态 更新时间:2024-10-19 00:24:33
实体框架中的Lazy和Eager加载在两者中使用.Include()时会得到相同的结果吗?(Lazy and Eager Loading in Entity Framework gives same result while using .Include() in both?)

我试图在EF中实现懒惰和急切的加载。 一切似乎都很好,但.Include()方法在两种情况下都可用,并返回相同的结果,无论延迟加载false还是true。

我有2个表类别和产品。 类别可以有多个产品和使用外键相关。

当我使用.Include("Products")使用延迟加载加载类别时,它会加载与类别相关的所有产品。

急切加载显示了相同的行为。

var results = objDB.Categories.Include("Products").ToList(); // Enabled lazy load var results = objDB.Categories.Include("Products").ToList(); // Disabled lazy load

两条线上方都有相同的结果。 请澄清这种混乱。

如果延迟加载= true,则不能使用.Include 。

请提出宝贵的意见。 提前致谢。

I have tried to implement lazy and eager loading in EF. Everything seems fine, but the .Include() method is available in both cases and returns the same results irrespective of lazy loading false or true.

I have 2 tables categories and product. Category can have multiple products and related using foreign key.

When I load categories using lazy loading by using .Include("Products"), it loads all products related to categories.

Same behavior is shown by eager loading.

var results = objDB.Categories.Include("Products").ToList(); // Enabled lazy load var results = objDB.Categories.Include("Products").ToList(); // Disabled lazy load

Above both lines have same result. Please clarify this confusion.

.Include should not be available in case of lazy loading = true.

Please give your valuable opinion. Thanks in advance.

最满意答案

当您明确使用Include() ,您正在执行Eager Loading。 显然,禁用/启用延迟加载不起作用。

当您省略Include并尝试访问某些Category实例中的Products navigation-property时,将反映出这种差异。 启用Lazy-Loading后,EF将从数据库加载它。 当它被禁用时,你将获得null 。

When you're explicitly using Include(), you're preforming an Eager Loading. Obviously, disabling/enabling Lazy Loading has no effect.

The difference will be reflected when you'll omit the Include and try to access the Products navigation-property in some of your Category instances. When Lazy-Loading is enabled, EF will load it from the database. When it's disabled, you'll get null.

更多推荐

本文发布于:2023-07-04 17:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026933.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时会   实体   框架   加载   Lazy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!