2011-02-16 114 views
2

我得到'Sequence contains no elements'with LINQ FirstOrDefault。序列不包含LINQ的元素FirstOrDefault

int? locationId = _ctx.m_locations.FirstOrDefault(
         l => l.name.ToLower() == countyOrTown.ToLower() 
       ).location_key; 

我认为FirstOrDefault的整点是,如果在数据库中没有条目不会引发异常,只是返回null?

+4

即便如此,当`null`返回时,您如何成功访问`location_key`? – 2011-02-16 16:08:45

+1

什么是堆栈跟踪? – SLaks 2011-02-16 16:09:19

回答

6

因为就像你说的你自己,.FirstOrDefault()将返回一个NULL值,需要首先检查为NULL,并且只有当它的NOT NULL然后访问它的属性.location_key

int? locationId = null; 

var firstOrDefault = _ctx.m_locations.FirstOrDefault(l => l.name.ToLower() == countyOrTown.ToLower()); 

if(firstOrDefault != null) 
    locationId = firstOrDefault.location_key; 
1

你意识到你正试图调用一个对象的“location_key”属性,可能会是NULL,对吧?

0

你确定它会抛出一个“Sequence contains [...]”而不是null异常吗?

如果查询确实返回“默认”(或空在这里)你的代码会抛出:

(空).location_key

0

测试m_locations和COUN tyOrTown为空引用,首先!您可能没有实例化该对象。

另外,(您可能已经这样做了)您应该验证countyOrTown不包含空字符串,并且数据中没有拼写错误,导致不匹配。