【问题标题】:Invalid Operation Exception was unhandled by user code用户代码未处理无效操作异常
【发布时间】:2018-03-30 05:44:05
【问题描述】:

大家好,有人可以在这里给我帮助吗?我是新手,我不知道该怎么办!错误指向它所说的 SqlDataReader rdr = cmd.ExecuteReader(),

System.Data.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理

我的代码在下面。提前致谢。

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

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();
    }
}

}

索引.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>

【问题讨论】:

  • 您的存储过程显然有问题。你自己调试过吗?
  • 请包含完整的异常详细信息(包括堆栈跟踪)。请附上wsp_Test01的源代码。
  • 等待生病编辑我的帖子
  • 如前所述,您的存储过程存在问题。没有该代码,就无法提供帮助。该错误还表明您没有捕获错误,如果您捕获了错误,您将能够看到异常,这将提供更多详细信息。
  • 已经编辑完毕

标签: c# sql-server asp.net-mvc stored-procedures model-view-controller


【解决方案1】:

在创建 SqlConnection 时,您有两个 using 语句。在您的 SqlCommand cmd 中,您使用的是第一个连接 - conObj,但您使用 conn.Open() 打开第二个连接。 省略第二个 SqlConnection 使用,然后打开第一个。 也可以放入使用SqlDataReader创建。

编辑:正如 NightOwl888 所建议的,指出连接未打开的问题,这是更改后的代码。 编辑 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
        }
    }
}

【讨论】:

  • 但是为什么会导致异常呢?通常可以有两个到数据库的连接。
  • AFAIK 如果不先打开与该命令关联的连接,您将无法执行该命令。因此,您会遇到异常。
  • 我看到当 Visual Studio 显示错误时,它直接在错误“其他信息:ExecuteReader 需要一个打开且可用的连接。连接的当前状态已关闭。”我猜原来的海报 J. Mar 错过了。
  • @Thomas - 我同意你的评价。但是,为了清楚起见,除了更正说明之外,您最好发布更正后的代码。
  • @Thomas 感谢您的代码,它在我的控制器中运行,但现在我收到新错误,它与我的模型有关,它说传递到字典中的模型项的类型为“AIStestv01.Models.EmpListModel” ,但此字典需要“System.Collections.Generic.IEnumerable`1[AIStestv01.Models.EmpListModel]”类型的模型项。
【解决方案2】:

首先,您不需要两个连接来执行此操作。一个单一的连接就可以了。其次,问题似乎与查询返回的字段的数据类型有关。尝试使用 '?.ToString()' 而不是 Convert.ToString。此外,请考虑处理来自数据库的数据类型。例如,C#中可以将DateTime列转换为DateTime,然后可以使用ToString('format')提取值。

另一个建议是从数据读取器循环中删除所有列,并开始一一添加,这样您就可以隔离导致问题的列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2018-10-25
    • 1970-01-01
    相关资源
    最近更新 更多