【问题标题】:sequence contains no elements Error Max() [duplicate]序列不包含元素错误 Max() [重复]
【发布时间】:2016-08-15 13:47:50
【问题描述】:

我得到了:

序列不包含任何元素

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;
}

【问题讨论】:

  • 使用 C#6,您可以使用 ?. 运算符轻松地将 int 提升为 int?,从而将整个方法简化为 return _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid).Max(t => t?.id);

标签: c# entity-framework linq


【解决方案1】:

您的查询未返回任何ids。这就是为什么例外。如果您的id 类型是int?,则使用DefaultIfEmpty(),例如:

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

其他选项是检查 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;
} 

【讨论】:

  • 上述查询的行为类似于 OR 而不是 AND 操作我在这里缺少什么 SELECT TOP 1 MAX(id) FROM sequenceTemplateItems sti WHERE sti.templateid = (some value) OR sti.contentitemid = null 应该返回 Null 而不是值
  • 我使用分析器进行监控,它正在创建这个 exec sp_executesql N'SELECT [Extent1].[id] AS [id] FROM [dbo].[sequenceTemplateItems] AS [Extent1] WHERE ([Extent1 ].[templateId] = @p__linq__0) AND (([Extent1].[contentItemId] = @p__linq__1) OR (([Extent1].[contentItemId] IS NULL) AND (@p__linq__1 IS NULL)))',N'@ p__linq__0 int,@p__linq__1 int',@p__linq__0=12742,@p__linq__1=NULL 但我希望它像这样运行 SELECT TOP 1 MAX(id) FROM sequenceTemplateItems sti WHERE sti.templateid = 12740 AND sti.contentitemid = null
猜你喜欢
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多