2016-05-12 14 views
0

陣列我想爲我的網站創建購物車的界限之外,我有這個下面我的購物車控制線:指數在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(); 
    } 
} 

當我運行項目爲第一次在我的購物類下面的行拋出此異常:

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 &關係類型,RelationshipSet & relationshipSet)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 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(布爾addRelationshipAsUnchanged,布爾doAttach)+210 System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(布爾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.InternalSet 1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +355 System.Data.Entity.Internal.Linq.InternalSet 1。添加(對象實體)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步驟,布爾& completedSynchro )+155

注意:當我向cartItem添加新購物車時,產品有factorDetail fielde,它是空的,所以它有關係嗎?

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

因此,如何我解決了這個例外?

+0

這些'storeDB.Carts.Add(cartItem)'調試器中的哪一個告訴你爲空? 'storeDB','Carts'或者'cartItem'? – Jasen

+0

目前尚不清楚 –

回答

0

Ofcourse這會拋出異常。因爲你是在將購物車添加到數據庫之前實例化一個新的ProductEntities類。

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

刪除此storeDB = new ProductEntities(); 您已經實例化ProductEntities()上的第一行代碼中ShoppingCart.cs

,因爲創建一個新的實例會忘記所有的對象在以前的環境。 和新的上下文在cartitem中添加空值。