简体   繁体   English

InvalidCastException:指定的强制转换在LINQ查询中无效

[英]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: 我在此行收到InvalidCastException错误:

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

The type of Count is int. Count的类型为int。 It works when I comment out this line of code. 当我注释掉这行代码时,它起作用。

UPDATE 更新

usp_getCountPerID looks like this: usp_getCountPerID看起来像这样:

@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 如果您从数据库返回计数,则可能必须转换为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. 如果失败,您还可以检查Counttype ,这可能有助于找出发生了什么情况。

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

Or perhaps the Database is returning null so try 或数据库返回null ,请尝试

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 它返回一个包含ID和每个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.. 因此,我没有获取foreach循环中每个ID的计数值,而是在进入foreach循环之前检索了ID和Count的列表,这可行。

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. 非常感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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