komeil shahmoradi
komeil shahmoradi

Reputation: 321

Index was outside the bounds of the array in mvc

I Want to create shopping cart for my site , i have this below lines for my shopping cart controller:

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

This below classes for my shopping cart model in model folder:

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

When I Run Project for first time the below line in ShoppingCart class throw this Exception:

storeDB.Carts.Add(cartItem);// Error Error

Object reference not set to an instance of an object.

But some times throwing this Exception:

Index Out Of Bound Of Array

And this Below line for my stacktrace:

[NullReferenceException: Object reference not set to an instance of an object.] System.Data.Entity.Core.Metadata.Edm.MetadataOptimization.GetCSpaceAssociationType(AssociationType osAssociationType) +38 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.FindRelationshipSet(ObjectContext context, EntitySet entitySet, EdmType& relationshipType, RelationshipSet& 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.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(Object entity) +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 parameters) +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, 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& completedSynchronously) +155

Note: when i add new cart to cartItem, product have factorDetail fielde that is null so Does it matter?

Note 2 : I Using this tutorial Part 8: Shopping Cart with Ajax Updates | The ASP.NET Site

So how i fixed this Exception?

Upvotes: 0

Views: 3092

Answers (1)

Rajput
Rajput

Reputation: 2607

Ofcourse this will throw exception. because you are you are instantiating a new ProductEntities class just before adding cart to db.

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

remove this storeDB = new ProductEntities(); you have already instantiated ProductEntities() on first line of code in ShoppingCart.cs

because creating a new instance will forgot all your object in previous context. and new context has null value in cartitem to add.

Upvotes: 1

Related Questions