简体   繁体   English

用户代码未处理无效的操作异常

[英]Invalid Operation Exception was unhandled by user code

Hello guys can someone pls give me help here I'm newbie and I don't know what to do! 大家好,有人可以在这里给我帮助吗,我是新手,我不知道该怎么办! the error is point to the SqlDataReader rdr = cmd.ExecuteReader() it says , 错误是指向SqlDataReader rdr = cmd.ExecuteReader(),它说,

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code System.Data.dll中发生类型'System.InvalidOperationException'的异常,但未在用户代码中处理

My codes is in below. 我的代码在下面。 Thanks in advance. 提前致谢。

EmpListModel EmpListModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;

namespace AIStestv01.Models
{
    public class EmpListModel
    {
        public string BioID { get; set; }
        public string Fullname { get; set; }
        public string Dthired { get; set; }
        public string DeptID { get; set; }
        public string Active { get; set; }
        public string NTLogin { get; set; }
    }
}

EmpController EmpController

using AIStestv01.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace AIStestv01.Controllers.AdminControllers
{
public class EmpController : Controller
{
    // GET: Emp
    public ActionResult Index()
    {
        var con = ConfigurationManager.ConnectionStrings["WOPcon"].ConnectionString;
        using (SqlConnection conObj = new SqlConnection(con))
        {
            SqlCommand cmd = new SqlCommand("wsp_Test01", conObj);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;

            var model = new List<EmpListModel>();
            using (SqlConnection conn = new SqlConnection(con))
            {
                conn.Open();
                SqlDataReader rdr = cmd.ExecuteReader(); //it says this is the error
                while (rdr.Read())
                {
                    var emp = new EmpListModel();
                    emp.BioID = Convert.ToString(rdr["BioID"]);
                    emp.Fullname = Convert.ToString(rdr["Fullname"]);
                    emp.Dthired = Convert.ToString(rdr["Dthired"]);
                    emp.DeptID = Convert.ToString(rdr["DeptID"]);
                    emp.Active = Convert.ToString(rdr["Active"]);
                    emp.NTLogin = Convert.ToString(rdr["NTLogin"]);

                    model.Add(emp);
                }
            }
        }

        return View();
    }
}

} }

Index.cshtml Index.cshtml

@model IEnumerable<AIStestv01.Models.EmpListModel>  

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<table>
    <tr>
        <th>Bio ID</th>
        <th>FUllname</th>
        <th>Date Hired</th>
        <th>Dept ID</th>
        <th>Active</th>
        <th>NT LOgin</th>
    </tr>
    @foreach (var emp in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => emp.BioID)</td>
            <td>@Html.DisplayFor(modelItem => emp.Fullname)</td>
            <td>@Html.DisplayFor(modelItem => emp.Dthired)</td>
            <td>@Html.DisplayFor(modelItem => emp.DeptID)</td>
            <td>@Html.DisplayFor(modelItem => emp.Active)</td>
            <td>@Html.DisplayFor(modelItem => emp.NTLogin)</td>
        </tr>
    }
</table>

You have two using statements with the SqlConnection creation. 在SqlConnection创建中有两个using语句。 In your SqlCommand, cmd, you are using the first connection - conObj, but you open with the conn.Open() the second connection. 在SqlCommand cmd中,您正在使用第一个连接-conObj,但是使用conn.Open()打开第二个连接。 Leave out the second SqlConnection using, and open the first one. 省略使用的第二个SqlConnection,然后打开第一个。 Also it is ok to put in the using the SqlDataReader creation. 也可以使用SqlDataReader创建来放入。

Edit: As suggested by NightOwl888 to point out the issue with the connection not opened, this is the changed code. 编辑:根据NightOwl888的建议,指出未打开连接的问题,这是更改后的代码。 Edit 2: I've changed the return statement to include model list into the returning view. 编辑2:我已经更改了return语句,以将模型列表包括到返回视图中。

using AIStestv01.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace AIStestv01.Controllers.AdminControllers
{
    public class EmpController : Controller
    {
        // GET: Emp
        public ActionResult Index()
        {
            var con = ConfigurationManager.ConnectionStrings["WOPcon"].ConnectionString;
            using (SqlConnection conObj = new SqlConnection(con))
            {
                SqlCommand cmd = new SqlCommand("wsp_Test01", conObj);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                var model = new List<EmpListModel>();

                conObj.Open();//Openning of the connection associated with the sql command

                using (SqlDataReader rdr = cmd.ExecuteReader())//Using around the SqlDataReader to dispose it after use
                {
                    while (rdr.Read())
                    {
                        var emp = new EmpListModel();
                        emp.BioID = Convert.ToString(rdr["BioID"]);
                        emp.Fullname = Convert.ToString(rdr["Fullname"]);
                        emp.Dthired = Convert.ToString(rdr["Dthired"]);
                        emp.DeptID = Convert.ToString(rdr["DeptID"]);
                        emp.Active = Convert.ToString(rdr["Active"]);
                        emp.NTLogin = Convert.ToString(rdr["NTLogin"]);

                        model.Add(emp);
                    }
                }
            }

            //do something with the 

            return View(model);//added model to use it in cshtml
        }
    }
}

First of all, you don't need two connections to perform this operation. 首先,您不需要两个连接即可执行此操作。 A single connection will do the trick. 单个连接即可解决问题。 Second, it seems the problem is related to the Data Type of the fields returned by your query. 其次,问题似乎与查询返回的字段的数据类型有关。 Try using a '?.ToString()' instead of that Convert.ToString. 尝试使用“?.ToString()”代替该Convert.ToString。 Also, consider handling the data type that comes from the database. 另外,请考虑处理来自数据库的数据类型。 For instance, DateTime columns can be converted to DateTime in C#, then you can use ToString('format') to extract the value. 例如,DateTime列可以在C#中转换为DateTime,然后可以使用ToString('format')提取值。

Another suggestion is to remove all columns from your Data Reader loop, and start adding one by one, so you can isolate the one that is causing the issue. 另一个建议是从Data Reader循环中删除所有列,并开始一个一个地添加,这样您就可以隔离引起问题的列。

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

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