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

问题描述

我有两个对象类

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)

我想我都错了

推荐答案

这是错误的

virtual"关键字用于不加载实体,除非您明确这一点(使用包含"语句)

延迟加载意味着当您第一次访问集合或导航属性时,实体将自动加载,并且这将透明地发生,就好像它们总是与父对象一起加载一样.

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.

使用include"是按需加载,当您指定要查询的属性时.

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

virtual 关键字的存在仅与延迟加载有关.virtual 关键字允许实体框架运行时为实体类及其属性创建动态代理,并由此支持延迟加载.如果没有虚拟,将不支持延迟加载,并且您在集合属性上会得到 null.

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.

事实上,您可以在任何情况下使用include",但没有延迟加载,它是访问集合和导航属性的唯一方法.

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.

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

10-28 04:30