序列不包含元素Error Max()

Ric*_*ard 10 c# linq entity-framework

我正进入(状态:

序列不包含任何元素

private int? GetPrecedingSibling(int? contentid,int? templateid)
{
    var value = _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid).Select(t => t.id).Max();
    if (value != 0)
        return value; 
    return null;
}
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 20

您的查询没有返回任何ids.这就是为什么例外.如果您的id类型int?使用DefaultIfEmpty()如下:

var value = _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid)
                    .Select(t => t.id)
                    .DefaultIfEmpty()
                    .Max();
Run Code Online (Sandbox Code Playgroud)

其他选项是检查Any记录然后返回Max或null.

var tempResult = _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid)
                    .Select(t => t.id);

if (tempResult.Any())
{
    return tempResult.Max();
}
else
{
    return null;
} 
Run Code Online (Sandbox Code Playgroud)