【问题标题】:Index was outside the bounds of the array in mvc索引超出了 mvc 中数组的范围
【发布时间】:2016-08-21 19:39:00
【问题描述】:

我想为我的网站创建购物车,我的购物车控制器有以下几行:

public ActionResult AddToCart(int id)
    {
        repository = new Repository();
        // Retrieve the album from the database
        var addedProduct = repository.FindProductByIdSingle(id);

        // Add it to the shopping cart
        var cart = ShoppingCart.GetCart(this.HttpContext);

        cart.AddToCart(addedProduct);

        // Go back to the main store page for more shopping
        return RedirectToAction("Index","Home");
    }

模型文件夹中我的购物车模型的以下类:

购物车.cs

public class Cart
{
    public int RecordId { get; set; }
    public string CartId { get; set; }
    public int ProductId { get; set; }
    public int Count { get; set; }
    public System.DateTime DateCreated { get; set; }
    public virtual Product Product { get; set; }

}

Order.cs

public class Order
{
    public int OrderId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string State { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public decimal Total { get; set; }
    public System.DateTime OrderDate { get; set; }
    public List<OrderDetail> OrderDetails { get; set; }
}

OrderDetails.cs

public class OrderDetail
    {
        public int OrderDetailId { get; set; }
        public int OrderId { get; set; }
        public int ProductId { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public virtual Product product { get; set; }
        public virtual Order Order { get; set; }
    }

ProductEntities.cs

public class ProductEntities: DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Cart> Carts { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderDetail> OrderDetails { get; set; }

}

ShoppingCart.cs

public class ShoppingCart
{
     ProductEntities storeDB = new ProductEntities();
    string ShoppingCartId { get; set; }
    public const string CartSessionKey = "CartId";

     public static ShoppingCart GetCart(HttpContextBase context)
    {
        var cart = new ShoppingCart();
        cart.ShoppingCartId = cart.GetCartId(context);
        return cart;
    }

    // Helper method to simplify shopping cart calls
    public static ShoppingCart GetCart(Controller controller)
    {
        return GetCart(controller.HttpContext);
    }

    public void AddToCart(Product product)
    {
        // Get the matching cart and album instances
        var cartItem  = storeDB.Carts.SingleOrDefault(
            c => c.CartId == ShoppingCartId
            && c.ProductId == product.Id);

        if (cartItem == null)
        {
            // Create a new cart item if no cart item exists
            cartItem = new Cart
            {
                ProductId = product.Id,
                CartId = ShoppingCartId,
                Count = 1,
                DateCreated = DateTime.Now,
                Product = product                  
            };
            storeDB = new ProductEntities();
            storeDB.Carts.Add(cartItem);// Error Error
        }
        else
        {
            // If the item does exist in the cart, 
            // then add one to the quantity
            cartItem.Count++;
        }
        // Save changes
        storeDB.SaveChanges();
    }
}

当我第一次运行项目时,ShoppingCart 类中的以下行抛出此异常:

storeDB.Carts.Add(cartItem);// 错误错误

对象引用未设置为对象的实例。

但有时会抛出这个异常:

索引超出数组范围

我的堆栈跟踪的下面这一行:

[NullReferenceException:对象引用未设置为对象的实例。] System.Data.Entity.Core.Metadata.Edm.MetadataOptimization.GetCSpaceAssociationType(AssociationType osAssociationType) +38 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.FindRelationshipSet(ObjectContext 上下文,EntitySet entitySet,EdmType&relationshipType,RelationshipSet&relationSet)+202 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AttachContext(ObjectContext 上下文,EntitySet entitySet,MergeOption mergeOption)+312 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AttachContext(ObjectContext 上下文,MergeOption 合并选项)+178 System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.CreateRelatedEnd(RelationshipNavigation 导航,RelationshipMultiplicity sourceRoleMultiplicity,RelationshipMultiplicity targetRoleMultiplicity,RelatedEnd existingRelatedEnd)+627 System.Data.Entity.Core.Objects.DataClasses.RelationshipFixer2.System.Data.Entity.Core.Objects.DataClasses.IRelationshipFixer.CreateSourceEnd(RelationshipNavigation navigation, RelationshipManager relationshipManager) +116 System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.GetRelatedEnd(RelationshipNavigation navigation, IRelationshipFixer relationshipFixer) +129 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.GetOtherEndOfRelationship(IEntityWrapper wrappedEntity) +93 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach) +231 System.Data.Entity.Core.Objects.DataClasses.EntityReference1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach) +210 System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach) +164 System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity) +521 System.Data.Entity.Internal.Linq.c__DisplayClassd.b__c() +98 System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +355 System.Data.Entity.Internal.Linq.InternalSet1.Add(对象实体)+200 System.Data.Entity.DbSet1.Add(TEntity entity) +131 MobileShop.Models.ShoppingCart.AddToCart(Product product) in d:\Projects\Asp.net\MobileShop\MobileShop\Models\ShoppingCart.cs:46 MobileShop.Controllers.ShoppingCartController.AddToCart(Int32 id) in d:\Projects\Asp.net\MobileShop\MobileShop\Controllers\ShoppingCartController.cs:40 lambda_method(Closure , ControllerBase , Object[] ) +161 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 参数)+434 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 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.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +73 System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47 System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +62 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, 对象标签) +59 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult 结果) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690172 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

注意:当我将新购物车添加到 cartItem 时,产品的 factorDetail 字段为 null,所以这有关系吗?

注2:我使用本教程Part 8: Shopping Cart with Ajax Updates | The ASP.NET Site

那么我是如何修复这个异常的呢?

【问题讨论】:

  • 调试器告诉您这些storeDB.Carts.Add(cartItem) 中的哪个为空? storeDBCartscartItem?

标签: asp.net-mvc


【解决方案1】:

当然这会抛出异常。因为您是在将购物车添加到数据库之前实例化一个新的 ProductEntities 类。

storeDB = new ProductEntities(); storeDB.Carts.Add(cartItem);

删除这个storeDB = new ProductEntities(); 您已经在 ShoppingCart.cs 的第一行代码中实例化了 ProductEntities()

因为创建一个新实例会忘记之前上下文中的所有对象。 并且新的上下文在 caritem 中有 null 值来添加。

【讨论】:

    猜你喜欢
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多