2009-09-18 9 views
7

Come potrei scrivere qualcosa di simile in LINQ to entitàLinq if

sb.Append(" WHERE question.question_isdeleted = 0"); 
    if (catid != 0) 
     sb.AppendFormat(" AND (CatID IN ({0}))", catsSTR); 
    if(!string.IsNullOrEmpty(AuthorID)) 
     sb.Append(" AND (question_ownerid = @id)"); 

Credo di aver solo bisogno la sintassi di scrivere un caso condizionale in LINQ to entità

risposta

14

Vorrei usare la notazione del punto qui:

var query = questions.Where(q => !q.IsDeleted); 

if (catId != 0) 
{ 
    query = query.Where(q => cats.Contains(q.CatID)); 
} 
if (authorId != 0) 
{ 
    query = query.Where(q => q.OwnerId == authorId); 
} 

Si potrebbe scrivere il proprio metodo di estensione per fare questo un po 'più semplice:

public static IQueryable<T> OptionalWhere<T>(
    this IQueryable<T> source, 
    bool condition, 
    Expression<Func<T,bool>> predicate) 
{ 
    return condition ? source.Where(predicate) : source; 
} 

Si potrebbe quindi scrivere:

var query = questions.Where(q => !q.IsDeleted); 
        .OptionalWhere(catId != 0, q => cats.Contains(q.CatID)) 
        .OptionalWhere(authorId != 0, q => q.OwnerId == authorId); 
+0

Jon, adora il metodo di estensione OptionalWhere. Totalmente fantastico :)/me ruba quella pepita di platino ... –

+0

hey che è un codice fantastico ... bello – user161433

-1
where question.question_isdeleted = 0 
    && (catid != 0 
    ? catsStr.Contains(CatId.ToString()) 
    : question_ownerId == id) 

Non sono sicuro se le operazioni con le stringhe sono corrette, ma la logica sembra corretta.

+0

che causerebbe LINQ to Entities per cercare di tradurre l'intera istruzione SQL, che non avrebbe senso se 'catid' è sconosciuto nel database. Un ulteriore problema con questa risposta è che aggiungerebbe una clausola where * su * catsStr' * o * 'question_ownerId'. Questo non è quello che è stato chiesto. –

+1

Le variabili in LINQ alle entità diventano parametri in SQL, quindi è legale utilizzare catId qui. –

0

È possibile condizionalmente creare una query come questa:

var query = from q in questions 
      where q.question_isdeleted 
      select q; 
if(!string.IsNullOrEmpty(AuthorID)) 
{ 
    query = from q in query 
      where q.question_ownerid == AuthorID 
      select q; 
} 

Tuttavia, LINQ to Entities non hanno buon costrutto analogo al SQL IN operator ...