Sequence不包含LINQ FirstOrDefault的元素

时间:2011-02-16 16:06:55

标签: c# .net linq

我正在使用LINQ FirstOrDefault获取'Sequence contains no elements'。

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

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

4 个答案:

答案 0 :(得分: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 :(得分:1)

您确实意识到您正在尝试在可能为NULL的对象上调用“location_key”属性,对吗?

答案 2 :(得分:0)

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

如果您的查询确实返回“default”(或此处为null),则代码将抛出:

(空).location_key

答案 3 :(得分:0)

首先测试m_locations和countyOrTown的空引用!您可能没有实例化对象。

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