2016-07-09 9 views
1

ich zu sehen bin versucht, ob es ein besserer Weg, um die Abfrage zu schreiben unten, wenn es ein optionaler Parameter (CountryId), dieLINQ - ausschließen die Filter, wenn der Wert NULL ist

NULL sein kann
public static IEnumerable<Game> GameByMatchingName(this IRepositoryAsync<Game> repository, string searchCriteria, string countryId = null) 
     { 
      return repository 
       .Queryable() 
       .Where(x => (countryId != null ? x.CountryId == countryId : true) && x.Name.Contains(searchCriteria)) 
       .AsEnumerable(); 
     } 

Idealer , Möchte ich die Kriterien im Filter ausschließen, wenn CountryId NULL ist.

-Alan-

+0

@KhanhTO, würde ich die Suchkriterien überprüfen fehlt nicht, wenn die countryid NOT NULL ist ?. Die Bedingung ist entweder nicht oder sollte aber die Prüfung auf countryId ignorieren, aber noch die Suchkriterien überprüfen –

+0

@KhanhTO, sucht das oben für countryId (s), die Null in db sind? CountryId ist FK in der Datenbank und es ist kein Nullable-Feld –

+0

Nicht sicher, ob dies funktioniert: 'var query = repository.Queryable(). Wo (x => x.Name.Contains (searchCriteria)); if (countryId! = Null) { query = query.Where (x => x.CountryId == countryId); } Rückgabe query.AsEnumerable(); ' –

Antwort

1
public static IEnumerable<Game> GameByMatchingName(this IRepositoryAsync<Game> repository, string searchCriteria, string countryId = null) 
    { 
     return repository 
      .Queryable() 
      .Where(x => (countryId == null) || (x.CountryId == countryId && x.Name.Contains(searchCriteria)).AsEnumerable(); 
    } 
0

Können Sie es in den Schritten nicht bauen:

public static IEnumerable<Game> GameByMatchingName(this IRepositoryAsync<Game> repository, string searchCriteria, string countryId = null) 
    { 
     var ret = repository 
      .Queryable() 
      .Where(x=>x.Name.Contains(searchCriteria)); 

      if (!(countrId == null)) 
      { 
      ret = ret.Where(y=>y.CountryId == countryId) 
      } 
     return ret.AsEnumerable();; 
    } 
Verwandte Themen