首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >int为null时如何创建请求并全部取走

int为null时如何创建请求并全部取走
EN

Stack Overflow用户
提问于 2019-04-29 00:51:04
回答 1查看 60关注 0票数 1

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

如果字符串可以为空,我可以使用someString.Contains(null ?? string.Empty)

和我的请求全部给出,但是如果我的int是null take all呢?要不然我就不想赚太多了

代码语言:javascript
运行
复制
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();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-29 01:03:44

而不是在查询内部创建这么多条件,而是在外部执行:

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
public int? SomeValue;

然后:

代码语言:javascript
运行
复制
if (model.SomeValue != null)
{
    query = query.Where(x => x.SomeValue == model.SomeValue);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55892519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档