linq to entities如果filter参数为null则选择所有实体?

时间:2013-08-03 14:39:15

标签: linq entity-framework

我使用ID过滤实体,但如果ID为null,那么我想返回所有实体。所以在下面的代码中,如果competitorID为null id,则返回所有简短的竞争对手。

var competitors =
                NeptuneUnitOfWork.Briefs.FindWhere(b => b.ID == briefID)
                                 .Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID)).ToList();

2 个答案:

答案 0 :(得分:2)

通常你会这样做:

IQueryable<Brief> briefs = NeptuneUnitOfWork.Briefs.Where(b => b.ID == briefID);

if (competitorID != null)
{
    competitors = briefs.Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID));
}
else
{
    competitors = briefs.Select(b => b.BriefCompetitors);
}

从技术上讲,您可以将问题留给SQL Server:

// Note the || clause
competitors = briefs.Where(b => b.ID == briefID)
                    .Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID || competitorID == null));

答案 1 :(得分:1)

只是对@xanatos帖子的一个小改动

// Note the || clause
competitors = briefs.Where(b => b.ID == briefID && (competitorID == null || b.ID == competitorID));