简体   繁体   English

延迟加载实体框架

[英]Lazy loading Entity framework

I started with database first approach with a many to one relation between Employee and Department. 我从数据库优先方法开始,它在员工和部门之间具有多对一的关系。 Two partial classes were created by Entity framework: Department having collections of Employee and Employee having single object Department . 实体框架创建了两个部分类:具有Employee集合的Department和具有单个对象Department Employee

If I added virtual then Department loads the related employees. 如果我添加了virtual那么Department将加载相关的员工。 There is no Inhertence relation ship between two classes. 两个类之间没有继承关系。 both are TPT. 都是TPT。

I got this link saying 我得到这个链接

Lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. 延迟加载是通过创建派生代理类型的实例,然后重写虚拟属性以添加加载挂钩来实现的。

So how is this happening? 那怎么回事呢? Department is not the Parent for Employee . Department不是Employee的父母。

Entity framework navigation properties work differently depending on whether you use a database-first or code-first approach. 实体框架导航属性的工作方式有所不同,具体取决于您使用数据库优先还是代码优先的方法。 Here's an expanded snippet from the link you posted: 这是您发布的链接的扩展摘录:

When using POCO entity types , lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. 使用POCO实体类型时 ,通过创建派生代理类型的实例,然后重写虚拟属性以添加加载钩子,可以实现延迟加载。

"POCO" means "plain old CLR object," which are the classes you would create in a code-first approach. “ POCO”的意思是“普通的旧CLR对象”,这是您将以代码优先方式创建的类。 Since those classes don't have any inherent knowledge of EF, you have to define your properties in such a way that the EF proxies can connect them correctly. 由于这些类不具备EF的任何固有知识,因此必须以EF代理可以正确连接它们的方式定义属性。

Since you are using database-first, the classes are not "POCO." 由于您使用数据库优先,因此这些类不是“ POCO”。 They inherit from an entity framework base class that wires up the navigation properties for lazy loading. 它们从实体框架基类继承,该基类连接了导航属性以进行延迟加载。

It seems you are confused about how proxy can do this. 您似乎对代理如何执行此操作感到困惑。

So when you get the employee.Department property loaded with instance of Department , the instance employee is not of type Employee --instead it is of the type proxy class generated by EF and inherited from your Employee class. 因此,当您获得的Department 。实例加载了employee.Department属性时,实例employee的类型不是Employee而是EF生成并继承自Employee类的proxy class类。 The allows the proxy type to override the Department property from the Employee class and that property's get method fires the database query to load the department instance into memory. 允许代理类型覆盖Employee类中的Department属性,并且该属性的get方法触发数据库查询以将Department实例加载到内存中。

However you can also disable that behavior of proxy creation. 但是,您也可以禁用代理创建的行为。

DbContext.Configuration.ProxyCreationEnabled = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM