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
It may not be the best solution but I changed my stored procedure to get count to this:
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.