Sequence不包含LINQ FirstOrDefault的元素

jaf*_*ffa 2 .net c# linq

LINQ FirstOrDefault我得到'Sequence contains no elements'.

int? locationId = _ctx.m_locations.FirstOrDefault(
                       l => l.name.ToLower() == countyOrTown.ToLower()
                  ).location_key;
Run Code Online (Sandbox Code Playgroud)

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

mar*_*c_s 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;
Run Code Online (Sandbox Code Playgroud)

  • 这并不能解释为什么错误是`Sequence contains no elements`而不是`NullReferenceException`. (3认同)