Another System.InvalidOperationException: Sequence contains no elements (using .Any())

StackOverflow https://stackoverflow.com/questions/12730095

سؤال

Getting the exception on this line:

public bool isEngageOn()
    {
line 149  -> return chatUserRepository.Table.Where(c => c.TrackingOn).Any();
    }

TrackingOn is of type boolean.

.Any() is suppose to "Determine weather a sequence contains any elements", so why the exception "System.InvalidOperationException Sequence contains no elements" caught on Elmah?

Error:

System.InvalidOperationException: Sequence contains no elements
 at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
 at System.Linq.Queryable.Any[TSource](IQueryable`1 source)
 at sf2015.Models.DomainModels.Services.ChatServices.isEngageOn() in C:\....\ChatServices.cs:line 149

p.s.: Can't reproduce the error but it shows up on Elmah error logs sometimes.

Below is some of the code for the repository

public virtual IQueryable<T> Table
    {
        get
        {
            return this.Entities;
        }
    }

    private DbSet<T> Entities
    {
        get
        {
            if (_entities == null)
                _entities = Context.Set<T>();
            return _entities;
        }
    }
هل كانت مفيدة؟

المحلول

The proper use would be

return chatUserRepository.Table.Any(c => c.TrackingOn)

نصائح أخرى

The stack trace you've provided says that the exception is from .Single which does throw the mentioned exception if no elements are found. You can change the mentioned code to:

 return chatUserRepository.Table.Any(c => c.TrackingOn);

Which will do the same as your line.

I had exactly the same problem.

Was using the method Any() but the StackTrace shows error on the Single() method.

The cause of the problem was the method Seed() on the Entity Framework Code First Configuration class.

My Seed() method was using the Single() method on a table that has no registries.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top