首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >不能将可空int设置为LINQ查询的返回值?

不能将可空int设置为LINQ查询的返回值?
EN

Stack Overflow用户
提问于 2015-01-05 05:33:49
回答 5查看 6.1K关注 0票数 3

我想根据某些条件从表中检索Id。如果不满足条件,我只想返回默认值(在本例中,我假设为null)。这是我的密码:

代码语言:javascript
代码运行次数:0
运行
复制
int? circuitTypeId = cimsContext.CircuitTypes.FirstOrDefault(ct => ct.Name == circuitType).Id;

我假设,如果ct.NamecircuitType之间没有匹配,则返回的值是null。但是,在运行我的程序时,我会在这一行上看到一个错误,上面写着"Null reference exception“。我知道记录不在那里,但难道我不能将查询返回的null分配给我的nullable int变量吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-01-05 05:38:58

在分配null变量之前,首先应该检查circuitTypeId

代码语言:javascript
代码运行次数:0
运行
复制
int? circuitTypeId;

var circuitType = cimsContext.CircuitTypes.FirstOrDefault(ct => ct.Name == circuitType);
if(circuitType != null)
{
    circuitTypeId = circuitType.Id;
}
票数 2
EN

Stack Overflow用户

发布于 2015-01-05 05:42:06

你的假设是错误的,根据你的疑问:-

代码语言:javascript
代码运行次数:0
运行
复制
int? circuitTypeId = cimsContext.CircuitTypes
                                .FirstOrDefault(ct => ct.Name == circuitType).Id;

这将在找到match时返回int,但当没有名称与circuitType名称匹配时,它将抛出一个circuitType。你应该这么做:-

代码语言:javascript
代码运行次数:0
运行
复制
var circuitTypeObj = cimsContext.CircuitTypes
                                .FirstOrDefault(ct => ct.Name == circuitType);
int? circuitTypeId = circuitTypeObj == null ? (int?)null : circuitTypeObj.Id;
票数 5
EN

Stack Overflow用户

发布于 2015-01-05 05:41:35

试试这个:

代码语言:javascript
代码运行次数:0
运行
复制
int? circuitTypeId = cimsContext.CircuitTypes.Where(ct => ct.Name == circuitType).Select(p => p.Id).FirstOrDefault();
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27773941

复制
相关文章

相似问题

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