如何在没有很多条件的情况下提出正确的请求。
如果字符串可以为空,我可以使用someString.Contains(null ?? string.Empty)
和我的请求给出全部,但是如果我的int为null怎么办?我不想赚太多
var students = _context.Students.Where(x =>
x.FacultetId == Facultet &&
x.Profession.Contains(model.Profession ?? string.Empty) &&
x.City.Contains(model.City ?? string.Empty) &&
x.Course == model.Course &&
x.Specialization.Contains(model.Specialization ?? string.Empty
)
).ToList();
答案 0 :(得分:2)
除了在查询中创建许多条件外,还可以在外部进行操作:
var query = _context.Students.Where(x => x.FacultetId == Facultet);
// filter by profession if there is some value
if (!string.IsNullOrempty(model.Profession))
{
query = query.Where(x => x.Profession.Contains(model.Profession));
}
// continue with the rest of the filters...
// and only then execute the query
var students = query.ToList();
检查可为空的int
是相同的。
假设SomeValue
是
public int? SomeValue;
然后:
if (model.SomeValue != null)
{
query = query.Where(x => x.SomeValue == model.SomeValue);
}