38

I am Getting:

sequence contains no elements

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;
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Richard
  • 469
  • 1
  • 5
  • 9
  • 2
    With C#6 you can easily promote `int` to `int?` by using the `?.` operator, thus reducing the whole method to `return _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid).Max(t => t?.id);` – Ivan Stoev Aug 15 '16 at 13:55

1 Answers1

58

Your query is not returning any ids. That is why the exception. If your id type is int? then use DefaultIfEmpty() like:

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

The other options is to check for Any records and then return Max or 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;
} 
Habib
  • 219,104
  • 29
  • 407
  • 436
  • The above query is behaving like OR instead of AND operation What am I missing here SELECT TOP 1 MAX(id) FROM sequenceTemplateItems sti WHERE sti.templateid = (some value) OR sti.contentitemid = null should return Null and not a value – Richard Aug 15 '16 at 18:26
  • I used profiler to monitor and it is creating this 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 But I want it to run like this SELECT TOP 1 MAX(id) FROM sequenceTemplateItems sti WHERE sti.templateid = 12740 AND sti.contentitemid = null – Richard Aug 15 '16 at 18:39