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

问题描述

我有两个对象类

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    // Navigation
    public ICollection<Product> Products { get; set; }
}

public class Product
{
    public Guid Id { get; set; }

    // Navigation
    public User User { get; set; }
    public Guid User_Id { get; set; }

    public string Name { get; set; }
}

当我加载使用DataContext的用户,我得到的产品列表是空(这是确定)。

When i load a user using dataContext, i get the list of Products being null (this is ok).

如果我添加虚拟关键字产品列表,

If i add "virtual" keyword to Products list,

public virtual ICollection<Product> Products { get; set; }

当我加载用户,我得到的产品列表,以及

when i load the user, i get the Products list as well.

这是怎么回事?我认为,虚拟关键字用于不加载,除非你明确的实体这(使用包括语句)

Why is this happening? I thought that "virtual" keyword is used for not loading the entities unless you explicit this (using an "Include" statement)

我觉得我完全搞错了。

推荐答案

这是错误的。

虚拟关键字用于不加载,除非你的实体
  这明确(使用包括语句)

延迟加载意味着实体将被自动加载当您第一次访问集合或导航属性,这将透明发生,就好像他们总是加载父对象。

Lazy Loading means that entities will be automatically loaded when you first access collection or navigation property, and that will happen transparently, as though they were always loaded with parent object.

使用包括加载点播,当您指定要查询的属性。

Using "include" is loading on demand, when you specify properties you want to query.

虚拟关键字的存在仅与延迟加载。 虚拟关键字允许实体框架运行时创建的动态代理为你的实体类和它们的属性,并通过支持延迟加载。如果没有虚拟化,延迟加载将不被支持,你会得到的集合属性无效。

Existence of virtual keyword is related only to lazy loading. virtual keyword allows entity framework runtime create dynamic proxies for your entity classes and their properties, and by that support lazy loading. Without virtual, lazy loading will not be supported, and you get null on collection properties.

事实是,你可以用包括在任何情况下,但没有延迟加载它是访问收集和导航性能的唯一途径。

Fact is that you can use "include" in any case, but without lazy loading it is the only way to access collection and navigation properties.

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

10-28 04:30