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

时间:2018-03-20 19:46:17

标签: asp.net-mvc visual-studio entity-framework shopping-cart

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

下面是错误行100.

CartId和ShoppingCartId是字符串。

Rad 98:         public List<Cart> GetCartItems()
Rad 99:         {
Rad 100:            return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
Rad 101:        }
Rad 102:

[ArgumentNullException:Value不能为null。 Parameternamn:来源]    System.Linq.Queryable.Where(IQueryable 1 source, Expression 1谓词)+2713614

    public class Cart
    {
        [Key]
        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 Produkt Product { get; set; }
    }
}






using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.Data.Objects;


namespace Test123.Models
{
    public class ShoppingCart
    {
        Test123Entities storeDB = new Test123Entities();
     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(Produkt product)
        {
            // Get the matching cart and product instances
            var cartItem = storeDB.Carts.SingleOrDefault(
                c => c.CartId == ShoppingCartId
                && c.ProductId == product.Produkt1);

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

        public int RemoveFromCart(int id)
        {
            // Get the cart
            var cartItem = storeDB.Carts.Single(
                cart => cart.CartId == ShoppingCartId
                && cart.RecordId == id);

            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    itemCount = cartItem.Count;
                }
                else
                {
                    storeDB.Carts.Remove(cartItem);
                }
                // Save changes
               // storeDB.SaveChanges();
            }
            return itemCount;
        }

        public void EmptyCart()
        {
            var cartItems = storeDB.Carts.Where(
                cart => cart.CartId == ShoppingCartId);

            foreach (var cartItem in cartItems)
            {
                storeDB.Carts.Remove(cartItem);
            }
            // Save changes
           // storeDB.SaveChanges();
        }

        public List<Cart> GetCartItems()
        {
            return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
        }

        public int GetCount()
        {
            // Get the count of each item in the cart and sum them up
            int? count = (from cartItems in storeDB.Carts
                          where cartItems.CartId == ShoppingCartId
                          select (int?)cartItems.Count).Sum();
            // Return 0 if all entries are null
            return count ?? 0;
        }

        public decimal GetTotal()
        {
            // Multiply product price by count of that product to get 
            // the current price for each of those products in the cart
            // sum all product price totals to get the cart total
            decimal? total = (from cartItems in storeDB.Carts
                              where cartItems.CartId == ShoppingCartId
                              select (int?)cartItems.Count *
                              cartItems.Product.Pris).Sum();
            return total ?? decimal.Zero;
        }

        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();
            // Iterate over the items in the cart, 
            // adding the order details for each
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    ProductId = item.ProductId,
                    OrderId = order.OrderId,
                    UnitPrice = item.Product.Pris,
                    Quantity = item.Count
                };
                // Set the order total of the shopping cart
                orderTotal += (item.Count * item.Product.Pris);

                storeDB.OrderDetails.Add(orderDetail);

            }

            // Set the order's total to the orderTotal count
            order.Total = orderTotal;
            // Save the order
            storeDB.Orders.Add(order);
           // storeDB.SaveChanges();
            // Empty the shopping cart
            EmptyCart();
            // Return the OrderId as the confirmation number
            return order.OrderId;
        }

        // We're using HttpContextBase to allow access to cookies.
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] =
                        context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();
                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }
    }



}

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Test123.Models;
using Test123.ViewModel;


namespace Test123.Controllers
{

    // GET: ShoppingCart
    public class ShoppingCartController : Controller
    {
    Test123Entities storeDB = new Test123Entities();

    // GET: /ShoppingCart/
    public ActionResult Index()
    {
        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Set up our ViewModel
        var viewModel = new ShoppingCartViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal()
        };
        return View(viewModel);
    }

    // GET: /Store/AddToCart/5
    public ActionResult AddToCart(int id)
    {
        // Retrieve the product from the database
        var addedProduct = storeDB.Products
            .Single(product => product.Produkt1 == 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");
    }

    // AJAX: /ShoppingCart/RemoveFromCart/5
    [HttpPost]
    public ActionResult RemoveFromCart(int id)
    {
        // Remove the item from the cart
        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Get the name of the product to display confirmation
        string productName = storeDB.Carts
            .Single(item => item.RecordId == id).Product.Namn;

        // Remove from cart
        int itemCount = cart.RemoveFromCart(id);

        // Display the confirmation message
        var results = new ShoppingCartRemoveViewModel
        {
            Message = Server.HtmlEncode(productName) +
                " el lett távolítva a bevásárlókosárból.",
            CartTotal = cart.GetTotal(),
            CartCount = cart.GetCount(),
            ItemCount = itemCount,
            DeleteId = id
        };
        return Json(results);
    }

    // GET: /ShoppingCart/CartSummary
    [ChildActionOnly]
    public ActionResult CartSummary()
    {
        var cart = ShoppingCart.GetCart(this.HttpContext);

        ViewData["CartCount"] = cart.GetCount();
        return PartialView("CartSummary");
    }
}

}

购物车的抄袭

    public class Test123Entities
    {
        public  DbSet<Cart> Carts { get; set; }

        public DbSet<Produkt> Products { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<Kategori> Categories { get; set; }

    }
}

1 个答案:

答案 0 :(得分:1)

添加空检查

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

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

在这种情况下,您调用的WhereIEnumerable<TSource>的扩展方法。 Where

存在2次重载
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);

如您所见,第一个参数名称为&#34; source&#34;,错误为:

  

值不能为空。参数名称:source

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

相关问题