简体   繁体   English

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

[英]Value cannot be null. Parameter name: source MVC & EF

I have a problem with my code. 我的代码有问题。 I get this error message "Value cannot be null. Parameter name: source" 我收到此错误消息“值不能为空。参数名称:source”

Below is the error row 100. 下面是错误行100。

CartId and ShoppingCartId is strings. 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 cannot be null. [ArgumentNullException:值不能为null。 Parameternamn: source] System.Linq.Queryable.Where(IQueryable 1 source, Expression 1 predicate) +2713614 参数名:source] 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();
        }
    }



}

Controller Below 下方控制器

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

} }

Delecartion of Carts 手推车的运输

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

    }
}

Add null check 添加空检查

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

Every methods from System.Linq that takes Reference types will check if they are null if(source== null) and throw a ArgumentNullException if they are. 来自System.Linq的所有使用引用类型的方法都将检查if if(source== null)是否为null if(source== null)如果存在if(source== null)并抛出ArgumentNullException

In this case, you call Where that is an extension method for IEnumerable<TSource> . 在这种情况下,您调用WhereIEnumerable<TSource>的扩展方法。 There exists 2 overloading of Where 存在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);

As you can see, there are first parameter with name "source", the error is: 如您所见,第一个参数的名称为“ source”,错误为:

Value cannot be null. 值不能为空。 Parameter name: source 参数名称:来源

it means that Carts is null . 这意味着Cartsnull Add null check will solve the problem 添加null检查将解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM