值不能为空。参数名称:源MVC & EF

0 asp.net-mvc shopping-cart entity-framework visual-studio

我的代码有问题。我收到此错误消息“值不能为空。参数名称:源”

\n\n

下面是错误行 100。

\n\n

CartId 和 ShoppingCartId 是字符串。

\n\n
Rad 98:         public List<Cart> GetCartItems()\nRad 99:         {\nRad 100:            return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();\nRad 101:        }\nRad 102:\n
Run Code Online (Sandbox Code Playgroud)\n\n

[ArgumentNullException: 值不能为 null。\nParameternamn: 源]\n System.Linq.Queryable.Where(IQueryable 1 source, Expression1 谓词) +2713614

\n\n
    public class Cart\n    {\n        [Key]\n        public int RecordId { get; set; }\n        public String CartId { get; set; }\n        public int ProductId { get; set; }\n        public int Count { get; set; }\n        public System.DateTime DateCreated { get; set; }\n        public virtual Produkt Product { get; set; }\n    }\n}\n\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Data.Entity;\nusing System.Data.Objects;\n\n\nnamespace Test123.Models\n{\n    public class ShoppingCart\n    {\n        Test123Entities storeDB = new Test123Entities();\n     string ShoppingCartId { get; set; }\n\n        public const string CartSessionKey = "CartId";\n        public static ShoppingCart GetCart(HttpContextBase context)\n        {\n            var cart = new ShoppingCart();\n            cart.ShoppingCartId = cart.GetCartId(context);\n            return cart;\n        }\n\n        // Helper method to simplify shopping cart calls\n        public static ShoppingCart GetCart(Controller controller)\n        {\n            return GetCart(controller.HttpContext);\n        }\n        public void AddToCart(Produkt product)\n        {\n            // Get the matching cart and product instances\n            var cartItem = storeDB.Carts.SingleOrDefault(\n                c => c.CartId == ShoppingCartId\n                && c.ProductId == product.Produkt1);\n\n            if (cartItem == null)\n            {\n                // Create a new cart item if no cart item exists\n                cartItem = new Cart\n                {\n                    ProductId = product.Produkt1,\n                    CartId = ShoppingCartId,\n                    Count = 1,\n                    DateCreated = DateTime.Now\n                };\n                storeDB.Carts.Add(cartItem);\n            }\n            else\n            {\n                // If the item does exist in the cart, \n                // then add one to the quantity\n                cartItem.Count++;\n            }\n            // Save changes\n            //storeDB.Savechanges();\n        }\n\n        public int RemoveFromCart(int id)\n        {\n            // Get the cart\n            var cartItem = storeDB.Carts.Single(\n                cart => cart.CartId == ShoppingCartId\n                && cart.RecordId == id);\n\n            int itemCount = 0;\n\n            if (cartItem != null)\n            {\n                if (cartItem.Count > 1)\n                {\n                    cartItem.Count--;\n                    itemCount = cartItem.Count;\n                }\n                else\n                {\n                    storeDB.Carts.Remove(cartItem);\n                }\n                // Save changes\n               // storeDB.SaveChanges();\n            }\n            return itemCount;\n        }\n\n        public void EmptyCart()\n        {\n            var cartItems = storeDB.Carts.Where(\n                cart => cart.CartId == ShoppingCartId);\n\n            foreach (var cartItem in cartItems)\n            {\n                storeDB.Carts.Remove(cartItem);\n            }\n            // Save changes\n           // storeDB.SaveChanges();\n        }\n\n        public List<Cart> GetCartItems()\n        {\n            return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();\n        }\n\n        public int GetCount()\n        {\n            // Get the count of each item in the cart and sum them up\n            int? count = (from cartItems in storeDB.Carts\n                          where cartItems.CartId == ShoppingCartId\n                          select (int?)cartItems.Count).Sum();\n            // Return 0 if all entries are null\n            return count ?? 0;\n        }\n\n        public decimal GetTotal()\n        {\n            // Multiply product price by count of that product to get \n            // the current price for each of those products in the cart\n            // sum all product price totals to get the cart total\n            decimal? total = (from cartItems in storeDB.Carts\n                              where cartItems.CartId == ShoppingCartId\n                              select (int?)cartItems.Count *\n                              cartItems.Product.Pris).Sum();\n            return total ?? decimal.Zero;\n        }\n\n        public int CreateOrder(Order order)\n        {\n            decimal orderTotal = 0;\n\n            var cartItems = GetCartItems();\n            // Iterate over the items in the cart, \n            // adding the order details for each\n            foreach (var item in cartItems)\n            {\n                var orderDetail = new OrderDetail\n                {\n                    ProductId = item.ProductId,\n                    OrderId = order.OrderId,\n                    UnitPrice = item.Product.Pris,\n                    Quantity = item.Count\n                };\n                // Set the order total of the shopping cart\n                orderTotal += (item.Count * item.Product.Pris);\n\n                storeDB.OrderDetails.Add(orderDetail);\n\n            }\n\n            // Set the order\'s total to the orderTotal count\n            order.Total = orderTotal;\n            // Save the order\n            storeDB.Orders.Add(order);\n           // storeDB.SaveChanges();\n            // Empty the shopping cart\n            EmptyCart();\n            // Return the OrderId as the confirmation number\n            return order.OrderId;\n        }\n\n        // We\'re using HttpContextBase to allow access to cookies.\n        public string GetCartId(HttpContextBase context)\n        {\n            if (context.Session[CartSessionKey] == null)\n            {\n                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))\n                {\n                    context.Session[CartSessionKey] =\n                        context.User.Identity.Name;\n                }\n                else\n                {\n                    // Generate a new random GUID using System.Guid class\n                    Guid tempCartId = Guid.NewGuid();\n                    // Send tempCartId back to client as a cookie\n                    context.Session[CartSessionKey] = tempCartId.ToString();\n                }\n            }\n            return context.Session[CartSessionKey].ToString();\n        }\n    }\n\n\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

下面的控制器

\n\n
using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing Test123.Models;\nusing Test123.ViewModel;\n\n\nnamespace Test123.Controllers\n{\n\n    // GET: ShoppingCart\n    public class ShoppingCartController : Controller\n    {\n    Test123Entities storeDB = new Test123Entities();\n\n    // GET: /ShoppingCart/\n    public ActionResult Index()\n    {\n        var cart = ShoppingCart.GetCart(this.HttpContext);\n\n        // Set up our ViewModel\n        var viewModel = new ShoppingCartViewModel\n        {\n            CartItems = cart.GetCartItems(),\n            CartTotal = cart.GetTotal()\n        };\n        return View(viewModel);\n    }\n\n    // GET: /Store/AddToCart/5\n    public ActionResult AddToCart(int id)\n    {\n        // Retrieve the product from the database\n        var addedProduct = storeDB.Products\n            .Single(product => product.Produkt1 == id);\n\n        // Add it to the shopping cart\n        var cart = ShoppingCart.GetCart(this.HttpContext);\n\n        cart.AddToCart(addedProduct);\n\n        // Go back to the main store page for more shopping\n        return RedirectToAction("Index");\n    }\n\n    // AJAX: /ShoppingCart/RemoveFromCart/5\n    [HttpPost]\n    public ActionResult RemoveFromCart(int id)\n    {\n        // Remove the item from the cart\n        var cart = ShoppingCart.GetCart(this.HttpContext);\n\n        // Get the name of the product to display confirmation\n        string productName = storeDB.Carts\n            .Single(item => item.RecordId == id).Product.Namn;\n\n        // Remove from cart\n        int itemCount = cart.RemoveFromCart(id);\n\n        // Display the confirmation message\n        var results = new ShoppingCartRemoveViewModel\n        {\n            Message = Server.HtmlEncode(productName) +\n                " el lett t\xc3\xa1vol\xc3\xadtva a bev\xc3\xa1s\xc3\xa1rl\xc3\xb3kos\xc3\xa1rb\xc3\xb3l.",\n            CartTotal = cart.GetTotal(),\n            CartCount = cart.GetCount(),\n            ItemCount = itemCount,\n            DeleteId = id\n        };\n        return Json(results);\n    }\n\n    // GET: /ShoppingCart/CartSummary\n    [ChildActionOnly]\n    public ActionResult CartSummary()\n    {\n        var cart = ShoppingCart.GetCart(this.HttpContext);\n\n        ViewData["CartCount"] = cart.GetCount();\n        return PartialView("CartSummary");\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

}

\n\n

推车的指定

\n\n
    public class Test123Entities\n    {\n        public  DbSet<Cart> Carts { get; set; }\n\n        public DbSet<Produkt> Products { get; set; }\n        public DbSet<Order> Orders { get; set; }\n        public DbSet<OrderDetail> OrderDetails { get; set; }\n        public DbSet<Kategori> Categories { get; set; }\n\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Rom*_*syk 5

添加空检查

public List<Cart> GetCartItems()
{
  if(storeDB.Carts != null)
  {
    return storeDB.Carts
       .Where(cart => cart.CartId == ShoppingCartId)
       .ToList();
  }
  return new List<Cart>();
}
Run Code Online (Sandbox Code Playgroud)

System.Linq中采用引用类型的每个方法都会检查它们是否为 null,如果是则if(source== null)抛出 a 。ArgumentNullException

在本例中,您称其Where为 的扩展方法IEnumerable<TSource>。存在2个重载Where

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
Run Code Online (Sandbox Code Playgroud)

如您所见,第一个参数名为“source”,错误为:

值不能为空。参数名称:来源

这意味着Cartsnull。添加null检查即可解决问题