Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Entity Framework from loading all child objects

I'm currently using Entity Framework to build a Forum using ASP.NET MVC I Have 3 principal Models [Category] 1--* [Forum] 1--* [Post]

If i Had 5 Categories and each one have 4 Forums and each Forum have 1000 post and I want to display only Categories, When I do that is that mean i have selected the 20000 posts too ??

Because each Category object have a List<'Forum'> and each Forum object have List<'Post'> due to mapping and relations

like image 391
Charaf Avatar asked Jul 16 '16 23:07

Charaf


2 Answers

You can use lazy loading to prevent child objects from being retrieved. See here. Lazy loading should be enabled by default.

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed.

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. For example, when using the Blog entity class defined below, the related Posts will be loaded the first time the Posts navigation property is accessed:

public virtual ICollection<Post> Posts { get; set; } 

You can achieve specific eager loading by using .Include(). For example:

db.Forums.Include(i => i.Posts)
like image 53
Nic Avatar answered Sep 19 '22 17:09

Nic


Set lazyloading=false in dbcontext file.

like image 32
NIts577 Avatar answered Sep 22 '22 17:09

NIts577