简体   繁体   中英

Lazy loading of related entities not working with Entity Framework 4.1

We have a project using Entity Framework 4.1 Code First for data storage. It was coded in such a way that EF is abstracted behind a repository pattern. When entities are fetched from a repository, the dataset is passed a huge list of include strings telling it all the related entities that should also be fetched. This results in an insanely huge query which can take 10 seconds to run - even when there is no data in the database!

There is already a lot of code written using the repository to access the database, I need to improve the performance ideally without breaking the pattern.

I am trying to change things so that when searching the database, no include strings are passed to the dataset (or just minimal include strings). When entities are fetched from the database, their related entities will be loaded through lazy loading when they are first accessed.

I have a class called Donation with a navigational property like this:

public virtual Employee Donor { get; private set; }

Both Donation and Employee classes have a private parameterless constructor. When using the include string "Donor", I can fetch a list of Donations and they are returned with Donor attached.

When I fetch a Donation from the repository without the include string, Donor is usually returned as null. If co-incidentally I am logged in as the Employee in question, another query elsewhere in the system will have already fetched my Employee entity from the Employee repository. When this happens, Donation is returned with Employee set correctly! So clearly the data is being "lazy loaded" if it is already available from an earlier query. But in general I won't have already queried for the Donor and all the other entities.

Can anyone suggest what I could be doing wrong? Sorry for the long question. I can post more bits of code if needed, but it is quite disparate. Thanks in advance!

I believe if you follow the guidelines on this page, http://msdn.microsoft.com/en-us/library/dd468057.aspx you should get the result you are after. Speficially making your parameterless constructor protected and that should help.

But please, look at the rest of the guidance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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