【问题标题】:Am I using reader wrong or is it possible my reader has null values?我使用阅读器错误还是我的阅读器可能有空值?
【发布时间】:2016-02-29 01:23:39
【问题描述】:

我正在从事一个电子商务项目,但在阅读器方面遇到了一些麻烦。这是我的 ShoppingCartController 代码不起作用

public List<PRODUCT> GetCartItems()
    {
        SqlConnection sqlConnection1 = new SqlConnection("MyConnection");
        SqlCommand cmd = new SqlCommand("uspGetCart", sqlConnection1);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar).Value = User.Identity.GetUserName();
        sqlConnection1.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        List<PRODUCT> cartList = new List<PRODUCT>();
        PRODUCT product;

        while (reader.Read())
        {
            product = new PRODUCT();
            product.MANUFACTURER.ManufacturerName = reader["ManufacturerName"].ToString();
            product.Name = reader["Name"].ToString();
            product.Cost = decimal.Parse(reader["Cost"].ToString());
            cartList.Add(product);
        }
        sqlConnection1.Close();
        return cartList;
    }

我得到的错误是 对象引用未设置为对象的实例。

堆栈跟踪是

    [NullReferenceException: Object reference not set to an instance of an object.]
    SeeSharpBeans.Controllers.ShoppingCartController.GetCartItems() in c:\Users\Andrew\Documents\Visual Studio 2013\Projects\SeeSharpBeans\SeeSharpBeans\Controllers\ShoppingCartController.cs:54
    SeeSharpBeans.Controllers.ShoppingCartController.Index() in c:\Users\Andrew\Documents\Visual Studio 2013\Projects\SeeSharpBeans\SeeSharpBeans\Controllers\ShoppingCartController.cs:22
    lambda_method(Closure , ControllerBase , Object[] ) +101
    System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
    System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
    System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
    System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
    System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102



System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39

我的产品模型如下所示

public partial class PRODUCT
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public PRODUCT()
    {
        this.PURCHASES = new HashSet<Purchase>();
        this.TRANSACTIONS = new HashSet<TRANSACTION>();
    }

    public int ProductID { get; set; }
    public int ManufacturerID { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Cost { get; set; }

    public virtual MANUFACTURER MANUFACTURER { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Purchase> PURCHASES { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<TRANSACTION> TRANSACTIONS { get; set; }
}

【问题讨论】:

  • 你遇到了什么错误?
  • [NullReferenceException: 对象引用未设置为对象的实例。]
  • 为什么您的属性是虚拟的?这些是实体类吗?你为什么要明确地压制警告而不是听从他们的建议?
  • 我首先使用了数据库,所以这就是实体框架为我创建的
  • 我尝试取出虚拟部分,但没有任何改变

标签: c# .net reader


【解决方案1】:

如果您的数据不包含空值,那么可能的问题是您没有将 MANUFACTURER 属性初始化为 PRODUCT 构造函数中的值,这意味着当您尝试将 product.MANUFACTURER.ManufacturerName 设置为一个值。

另请注意,以全部大写字母命名类和成员通常是不好的形式 - 考虑将它们更改为 ProductManufacturer

【讨论】:

  • 如何在 PRODUCT 类中初始化它?
  • 某本书告诉我要全大写数据库类,我认为那是垃圾,但我就像我知道的一样,当我第一次做数据库时,它把 Product 和 Manufacturer 类放在全部大写
【解决方案2】:

我认为问题可能出在这条线上

product.MANUFACTURER.ManufacturerName = reader["ManufacturerName"].ToString();

MANUFACTURER 是否在 Product 类中初始化?

【讨论】:

  • 虚拟初始化了吗?
  • 不管是不是虚拟的。你可以这样做:product.MANUFACTURER = new MANUFACTURER();然后初始化 ManufaturerName
【解决方案3】:

尝试将集合项定义移动到while循环的范围内:

while (reader.Read()) 
{ 
PRODUCT product = new PRODUCT(); 
product.MANUFACTURER.ManufacturerName = reader["ManufacturerName"].ToString(); 

product.Name = reader["Name"].ToString();

product.Cost = decimal.Parse(reader["Cost"].ToString()); 
cartList.Add(product); }

【讨论】:

  • 尝试详细说明你的答案,以便其他人可以轻松理解你为什么采用这种方法。
【解决方案4】:
This line is the issue
product.MANUFACTURER.ManufacturerName = reader["ManufacturerName"].ToString();

Use
 product.MANUFACTURER.ManufacturerName = Convert.ToString(reader["ManufacturerName"])  

 product.Cost = decimal.Parse(Convert.ToString(reader["Cost"]));
instead of .ToString();

【讨论】:

  • 这给了我同样的错误。我做了一个干净和重建只是为了确保。
  • 这条线怎么样 product.Cost = decimal.Parse(reader["Cost"].ToString());
  • 它没有到达那条线,因为它在它之前中断
【解决方案5】:

需要使用他们的构造函数来初始化 MANUFACTURER:-

while (reader.Read())
            {
                product = new PRODUCT();
                product.MANUFACTURER=new MANUFACTURER();
                product.MANUFACTURER.ManufacturerName = reader["ManufacturerName"].ToString();
                product.Name = reader["Name"].ToString();
                product.Cost = decimal.Parse(reader["Cost"].ToString());
                cartList.Add(product);
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多