Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Conditionally include related entities

I maintain an API that, based on a request for a list of people, returns a different result set based on the request. For example, some API clients want to get a list of people and a list of their interactions, others want people and a list of their metadata. All this can be specified int he request to the API method that returns people.

This does not appear to work:

using (var dbcontext = new ExampleEntities())
{
    var query = dbcontext.People.AsQueryable();
    //determined in earlier application logic based on request
    if(includeMetadata)
    {
        query = query.Include("metadata");
    }
    //determined in earlier application logic based on request
    if(includeInteractions) 
    {
        query = query.Include("interactions");
    }
    /* ...SNIP... */
}

What I don't want to do is this:

var query = dbcontext.People.Include("Metadata").Include("interactions");

which will mean every request to get a person will include ALL their related entities, even if the requesting API client does not need them.

I also don't want to code every possible combination of logic:

if(includeMetadata && includeInteractions)
{
    var query = dbcontext.People.Include("Metadata").Include("interactions");

}
else if(includeMetadata)
{
    var query = dbcontext.People.Include("Metadata");
}
else if(includeInteractions)
{
    var query = dbcontext.People.Include("Interactions");
}
else
{
    var query = dbcontext.People;
}

This will result in hard-to-maintain code, however, I realize I could code generate this if needed.

like image 214
Julia McGuigan Avatar asked Dec 10 '13 20:12

Julia McGuigan


1 Answers

You can chain the IQueryable's

using (var dbcontext = new ExampleEntities())
{
    var query = dbcontext.People.AsQueryable();
    if(includeMetadata)
    {
        query = query.Include("metadata");
    }
    if(includeInteractions) 
    {
        query = query.Include("interactions");
    }    
}
like image 116
VahidN Avatar answered Sep 21 '22 21:09

VahidN