简体   繁体   中英

InvalidCastException: Specified cast is not valid in LINQ query

I am getting Specified cast is not valid error in this method

public Dictionary<byte, string> getTeamList(int id1, Dictionary<byte, int> myList)
{    
    Dictionary<byte, string> result = new Dictionary<byte, string>();
    var query= _dataContext.usp_getItem();
    foreach(var item in query)
    {
        if (myList.ContainsKey(item.ID)
        {
            int count= _dataContext.usp_getCountPerID(id1, item.ID).FirstOrDefault().Count;
            if (myList[item.ID] > count)
            {
                result.Add(item.ID, item.Name);
            }
        }
        else
        {
            result.Add(item.ID, item.Name);
        }
    }
    return result;
} 

I'm getting the InvalidCastException error at this line:

int count = _dataContext.usp_getCountPerID(item.ID).FirstOrDefault().Count;

The type of Count is int. It works when I comment out this line of code.

UPDATE

usp_getCountPerID looks like this:

@ID1 INT,
@ID2 TINYINT
SELECT COUNT(ID) AS Count  //I'm changing this name so it's actually not "Count"
FROM   Table
WHERE  ID1 = @ID1
       AND ID2 = @ID2

If your returning the count from the database you may have to cast as int

perhaps

int count = (int)_dataContext.usp_getCountPerID(item.ID).FirstOrDefault().Count;

or

int count = Convert.ToInt32(_dataContext.usp_getCountPerID(item.ID).FirstOrDefault().Count);

if that fails also you could check the type of object Count is which may help in finding out whats going on.

var count = _dataContext.usp_getCountPerID(item.ID).FirstOrDefault().Count;
Type t = count.GetType();

Or perhaps the Database is returning null so try

int? count = (int?)_dataContext.usp_getCountPerID(item.ID).FirstOrDefault().Count;

It may not be the best solution but I changed my stored procedure to get count to this:

@SessionID INT
SELECT ID, COUNT(Member) AS Count
FROM   Table
WHERE  SessionID = @SessionID 
GROUP BY ID

which returns a table containing ID and the total count of Members for each ID

So, instead of getting values for the count per ID inside the foreach loop, I retrieve the list of ID and Count before entering the foreach loop and this works..

I still don't understand why I was getting the casting error, so I would mark it as answer if someone could explain what I was missing.

Thank you so much for all your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM