Why am I getting a "Sequence contains no matching element" error when using .Any

0

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?

c#
sql
linq
asked on Stack Overflow Dec 15, 2017 by user3839756

2 Answers

0

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);
answered on Stack Overflow Dec 16, 2017 by Harald Coppoolse
-1

Is hard to see, with your example but probably you must check if you have Null values in "MyTable" and the datatypes of MyTable.Year,MyTable.Quarter and MyTable.Week match with the sames in MyObj...


User contributions licensed under CC BY-SA 3.0