使用LINQ时出错 [英] Error while using LINQ

查看:102
本文介绍了使用LINQ时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我正在使用LINQ.我得到一个错误.以下代码:

Hi all,
I am using LINQ. I get an error. Following code:

HRM_SamparkDataContext Obj1 = new HRM_SamparkDataContext();
        try
        {
            string CompId = string.Empty;
            HRM_SamparkDataContext Obj=new HRM_SamparkDataContext();
            string Ip = Context.Request.ServerVariables["REMOTE_ADDR"];
            var Res = from Log in Obj.Sp_Check_Head_Hr_Login(Tbx_Head_Hr_ID.Text.Trim(), Tbx_Pass.Text.Trim()) select Log;
           

            if (Res.Count() > 0)
            {
               // Session["CompID"] = Tbx_Head_Hr_ID.Text.Trim();
                Res = from Log in Obj.Sp_Check_Head_Hr_Login(Tbx_Head_Hr_ID.Text.Trim(), Tbx_Pass.Text.Trim()) select Log;
              <big>  CompId = Res.ElementAt(2).CompID;</big>
                Obj1.Sp_Insert_HeadHr_Login_Log(Tbx_Head_Hr_ID.Text.Trim(), CompId, Tbx_Pass.Text.Trim(), "Success", Ip);

              
            }
            else
            {
                Obj1.Sp_Insert_HeadHr_Login_Log(Tbx_Head_Hr_ID.Text.Trim(),CompId, Tbx_Pass.Text.Trim(), "Fail", Ip);
                this.ClientScript.RegisterStartupScript(this.GetType(), "Welcome at HRM Intranet", "<script language=\"javaScript\">" + "alert('Authentication Fail Try Again !');" + "<" + "/script>");
            }


        }
        catch (Exception Ex)
        {

        }



上面的代码给出了异常:
[System.ArgumentOutOfRangeException] = {指定的参数不在有效值范围内.\ r \ n参数名称:索引"} 引发异常的位置以粗体显示

有人可以告诉我解决方案吗?



The above code is giving Exception:
[System.ArgumentOutOfRangeException] = {"Specified argument was out of the range of valid values.\r\nParameter name: index"} from where the exception is thrown is shown in bold

Can any one tell me the solution?

推荐答案

检查Res变量,似乎它的值小于3,这就是为什么在索引时它会给您这个异常索引2的元素.
Check the Res variable, it seems it has less than 3 values, thats why its giving you this exception since you are indexing an element of index 2.


您没有为该操作检查null.检查Res.ElementAt(2)是否存在.

试试这个,
You are not checking null for that operation. Check if Res.ElementAt(2) exists or not.

Try this,
CompId = Res.ElementAt(2) ?? 0;

if(CompId !=0)
{
  Obj1.Sp_Insert_HeadHr_Login_Log(Tbx_Head_Hr_ID.Text.Trim(), CompId,   Tbx_Pass.Text.Trim(), "Success", Ip);
}


这不是准确的代码段.但是您可以进行相应的测试和修改.


This is not an accurate snippet. But you can test and modify accordingly.


这篇关于使用LINQ时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆