3

我使用 ID 过滤实体,但如果 ID 为空,那么我想返回所有实体。因此,在下面的代码中,如果竞争者 ID 为空 id,则希望返回所有简短的竞争者。

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

2 回答 2

3

通常你这样做:

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));
于 2013-08-03T14:44:13.707 回答
1

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

// Note the || clause
competitors = briefs.Where(b => b.ID == briefID && (competitorID == null || b.ID == competitorID));
于 2013-08-03T16:28:44.087 回答