当有一个可选参数(CountryId)可以为NULL时,我试图看看是否有更好的方法来编写下面的查询
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();
}
理想情况下,我想在CountryId为NULL时排除过滤器中的条件。
-Alan -
答案 0 :(得分: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();
}
答案 1 :(得分:0)
无法按步骤构建它:
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();;
}