索引超出了mvc

时间:2016-05-12 18:47:41

标签: asp.net-mvc

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

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

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

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

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

  

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

     

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

但是有时候会抛出这个例外:

  

索引超出数组

这是我的stacktrace的下面一行:

  

[NullReferenceException:对象引用未设置为对象的实例。]      System.Data.Entity.Core.Metadata.Edm.MetadataOptimization.GetCSpaceAssociationType(AssociationType osAssociationType)+38      System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.FindRelationshipSet(ObjectContext context,EntitySet entitySet,EdmType&amp; relationshipType,RelationshipSet&amp; relationshipSet)+202      System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AttachContext(ObjectContext context,EntitySet entitySet,MergeOption mergeOption)+312      System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AttachContext(ObjectContext context,MergeOption mergeOption)+178      System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.CreateRelatedEnd(RelationshipNavigation navigation,RelationshipMultiplicity sourceRoleMultiplicity,RelationshipMultiplicity targetRoleMultiplicity,RelatedEnd existingRelatedEnd)+627      System.Data.Entity.Core.Objects.DataClasses.RelationshipFixer 2.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.EntityReference 1.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。&lt;&gt; c__DisplayClassd.b__c()+98      System.Data.Entity.Internal.Linq.InternalSet 1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +355 System.Data.Entity.Internal.Linq.InternalSet 1.Add(Object entity)+200      System.Data.Entity.DbSet 1.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, IDictionary 2个参数)+434      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() +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.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult)+62      System.Web.Mvc.Async.WrappedAsyncResultBase 1.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.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult)+70      System.Web.Mvc.Async.WrappedAsyncResultBase`1.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.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)+40      System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)+38      System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+9690172      System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+155

注意:当我向cartItem添加新购物车时,产品的factorDetail fielde为null,这有关系吗?

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

那么我如何解决这个例外?

1 个答案:

答案 0 :(得分:1)

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

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

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

因为创建新实例会在之前的上下文中忘记所有对象。 并且新的上下文在cartitem中有空值以便添加。