3

ID を使用してエンティティをフィルタリングしていますが、ID が null の場合は、すべてのエンティティを返したいと考えています。以下のコードでは、competitorID が null id の場合、すべての briefcompetitors を返します。

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 に答える