如果int为空,如何创建请求并全部接受

时间:2019-04-28 16:51:04

标签: c# entity-framework-core

如何在没有很多条件的情况下提出正确的请求。

如果字符串可以为空,我可以使用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();

1 个答案:

答案 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);
}