实体框架-有条件地包括相关实体 [英] Entity Framework - Conditionally include related entities

查看:59
本文介绍了实体框架-有条件地包括相关实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我维护一个API,该API根据对人员列表的请求,根据该请求返回不同的结果集。例如,一些API客户端想要获取人员列表及其交互的列表,而其他API客户端则需要人员及其元数据的列表。所有这些都可以在请求返回人的API方法中指定。

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.

这似乎不起作用:

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... */
}

我不想这样做:

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

这意味着每一个获取人的请求都将包括其所有相关实体,即使请求API客户不需要它们。

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.

推荐答案

您可以链接IQueryable的

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");
    }    
}

这篇关于实体框架-有条件地包括相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆