C# – getting a “Sequence contains no matching element” error when using .Any

clinqsql

I have a .Any() Linq Method:

db.MyTable.Any(x => x.Year == MyObj.Year && x.Quarter == MyObj.Quarter && x.Week == MyObj.Week)

That is returning the error:

 System.InvalidOperationException occurred
  HResult=0x80131509
  Message=Sequence contains no matching element
  Source=EntityFramework

However the MSDN documentation states that the .Any method returns "true if the source sequence contains any elements; otherwise, false."

Why is this method throwing the exception instead of returning False?

Best Answer

With this little code it is fairly difficult to see what the cause is. It certainly is not in this part of the code.

Try to do some debugging, use the debugger to check all values, or write some Debugging statements before you perform your function:

// Check myObj
MyObjectType myObj = ...         // instead of var, so you are certain you have the right type
Debug.Assert(myObj != null);

// only if Year, Quarter, Week are classes:
Debug.Assert(myObj.Year != null);   
Debug.Assert(myObj.Quarter != null);
Debug.Assert(myObj.Week != null);

// check your db:
Debug.Assert(db != null);
Debug.Assert(db.MyTable != null);
int count1 = db.MyTable.Count();
int count2 = db.MyTable
    .Where(x => x.Year == MyObj.Year 
        && x.Quarter == MyObj.Quarter
        && x.Week == MyObj.Week)
    .Count();
bool hasAny = db.MyTable
    .Where(x => x.Year == MyObj.Year 
        && x.Quarter == MyObj.Quarter
        && x.Week == MyObj.Week)
    .Any();

// if all this works, your statement should also work
hasAny = db.MyTable
    .Any(x => x.Year == MyObj.Year 
        && x.Quarter == MyObj.Quarter
        && x.Week == MyObj.Week);