我正在尝试查看当有一个可选参数(CountryId)可以为空时是否有更好的方法来编写下面的查询
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 时排除过滤器中的条件。
-艾伦-
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();
}
你不能分步构建它吗:
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();;
}
我在jquery数据表服务器端过滤时遇到了这个问题。我的 solition 是 if 变量 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) || (countryId == null && x.CountryId == x.CountryId)) && x.Name.Contains(searchCriteria))
.AsEnumerable();
}
不允许
在 SQL 查询中无所事事地出现不必要的参数
public static IEnumerable<Game> GameByMatchingName(this IRepositoryAsync<Game> repository, string searchCriteria, string countryId = null)
{
if(countryId == null)
{
return repository
.Queryable()
.Where(x => x.Name.Contains(searchCriteria))
.AsEnumerable();
}
else {
return repository
.Queryable()
.Where(x => x.CountryId == countryId && x.Name.Contains(searchCriteria))
.AsEnumerable();
}
}