Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework eager loading based on a specific attribute

The current setup of EF in my application is lazy loading, which is great for the most part. However, I am lost trying work out how to load a list of related entities based on their IsEnabled bit attribute.

In this example I am just returning a list of entities.

return Context.Entities.ToList()

Let's say the Entities object contains a list of ChildEntities like so:

public class Entities
{        
    private string EntityName;

    private List<ChildEntities> ChildEntities;
}

public class ChildEntites
{        
    private string ChildEntityName;
    private bool IsEnabled;
}

I want to only want to get out the ChildEntities based on their IsEnabled flag when loading the list of Entities.

like image 392
cullimorer Avatar asked Dec 07 '25 05:12

cullimorer


1 Answers

You can use the Include() method to load all child entities and then select only those which are enabled like

Context.Entities.Include("ChildEntites").Select(c => e.IsEnabled == true)

Another way would be to get the filter entities and then run the query as shown in this post

var data = from e in Context.Entities
            select new
            {
                Entities = e,
                Childs = e.ChildEntites.Where(c => c.IsEnabled == true) 
            };

var Results = data.ToArray().Select(x => x.Entities);
like image 72
Rahul Avatar answered Dec 09 '25 19:12

Rahul