C# 实体框架代码优先延迟加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11469432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework Code First Lazy Loading
提问by Catalin
I am having two object classes
我有两个对象类
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; }
}
When i load a user using dataContext, i get the list of Products being null (this is ok).
当我使用 dataContext 加载用户时,我得到的产品列表为空(这没关系)。
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)
为什么会这样?我认为“虚拟”关键字用于不加载实体,除非您明确指出这一点(使用“包含”语句)
I think i got it all wrong
我想我都错了
采纳答案by archil
This is wrong
这是错误的
"virtual" keyword is used for not loading the entities unless you explicit this (using an "Include" statement)
“virtual”关键字用于不加载实体,除非您明确指出这一点(使用“Include”语句)
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.
当您指定要查询的属性时,使用“include”是按需加载。
Existence of virtualkeyword is related only to lazy loading. virtualkeyword 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.
virtual关键字的存在仅与延迟加载有关。virtual关键字允许实体框架运行时为您的实体类及其属性创建动态代理,并由此支持延迟加载。如果没有虚拟,将不支持延迟加载,并且您在集合属性上会得到 null。
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.
事实上,您可以在任何情况下使用“include”,但没有延迟加载,它是访问集合和导航属性的唯一方法。
回答by abatishchev
I guess you're quiring for a property which is a subject for lazy load while being intothe ef context:
我猜您正在寻找一个属性,该属性是在进入ef 上下文时进行延迟加载的主题:
using (var db = new Context())
{
var user = db.Users.Where(...);
var products = user.Products; // being loaded right away
}
Try to leave it:
尝试离开它:
User user;
using (var db = new Context())
{
user = db.Users.Where(...);
// I guess you will need here:
// .Include(u => u.Products)
}
var products = user.Products; // what error will you get here?

