3

我正在关注 MusicStore 教程,我已经在教程的第 8 部分。当我尝试添加 ShoppingCart 类时出现此错误。我尝试用谷歌搜索可能的解决方案,但未能找到干净的 T_T .. 根据我的研究,我收到此错误,因为我使用的是 edmx数据库优先而不是教程中的代码优先。

我添加了这些代码,并且在 Add() 和 Remove() 上出现错误

namespace Project.Models 
{ 
    public partial class ShoppingCart 
    {  
        ProjectEntities db = new ProjectEntities();  

        string ShoppingCartId { get; set; }

        public const string CartSessionKey = "cart_ID";
        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 = db.Carts.SingleOrDefault(c => c.cart_ID == ShoppingCartId && c.product_ID == product.product_ID);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new Cart
                {
                    product_ID = product.product_ID,
                    cart_ID = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };
                db.Carts.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,  then add one to the quantity
                cartItem.Count++;
            }
            // Save changes
            db.SaveChanges();
        }
        public int RemoveFromCart(int id)
        {
            // Get the cart
            var cartItem = db.Carts.Single(cart => cart.cart_ID == ShoppingCartId && cart.record_ID == id);

            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    itemCount = cartItem.Count;
                }
                else
                {
                    db.Carts.Remove(cartItem);
                }
                // Save changes
                db.SaveChanges();
            }
            return itemCount;
        }
        public void EmptyCart()
        {
            var cartItems = db.Carts.Where(cart => cart.cart_ID == ShoppingCartId);

            foreach (var cartItem in cartItems)
            {
                db.Carts.Remove(cartItem);
            }
            // Save changes
            db.SaveChanges();
        }
        public List<Cart> GetCartItems()
        {
            return db.Carts.Where(cart => cart.cart_ID == ShoppingCartId).ToList();
        }
        public int GetCount()
        {
            // Get the count of each item in the cart and sum them up
            int? count = (from cartItems in db.Carts
                          where cartItems.cart_ID == ShoppingCartId
                          select (int?)cartItems.Count).Sum();
            // Return 0 if all entries are null
            return count ?? 0;
        }
        public decimal GetTotal()
        {
            // Multiply album price by count of that album to get 
            // the current price for each of those albums in the cart
            // sum all album price totals to get the cart total
            decimal? total = (from cartItems in db.Carts
                              where cartItems.cart_ID == ShoppingCartId
                              select (int?)cartItems.Count * cartItems.Product.Price).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
                {
                    product_ID = item.product_ID,
                    order_ID = order.order_ID,
                    UnitPrice = item.Product.Price,
                    Quantity = item.Count
                };
                // Set the order total of the shopping cart
                orderTotal += (item.Count * item.Product.Price);

                db.OrderDetails.Add(orderDetail);

            }
            // Set the order's total to the orderTotal count
            order.Total = orderTotal;

            // Save the order
            db.SaveChanges();
            // Empty the shopping cart
            EmptyCart();
            // Return the OrderId as the confirmation number
            return order.order_ID;
        }
        // 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();
        }
        // When a user has logged in, migrate their shopping cart to
        // be associated with their username
        public void MigrateCart(string userName)
        {
            var shoppingCart = db.Carts.Where(c => c.cart_ID == ShoppingCartId);
            foreach (Cart item in shoppingCart)
            {
                item.cart_ID = userName;
            }
            db.SaveChanges();
        }
    }
}  

我是 MVC 的初学者,希望有人能帮助我解决这个问题。

4

4 回答 4

4

好的,我做了什么来使它工作..而不是使用 .Add() 我使用 .AddObject() 而不是使用 .Remove 我使用 .DeleteObject() .. 我不知道这件事背后的原因,但是至少它不再显示错误消息了.. :P 感谢所有帮助我的人.. :)

于 2012-12-19T07:23:39.670 回答
2

添加和删​​除来自 EntityFrame 命名空间 System.Data.Entity

所以我的猜测是使用 System.Data.Entity缺失?还要检查项目中添加的参考 EntityFramework.dll 吗?或者使用包管理器(nuget)在项目中添加 EF?,您的上下文是否来自 DBContext?如果不是没有添加。如果您看到 AddObject,您很可能是从 ObjectContext 派生的

于 2012-12-19T03:04:20.833 回答
0
public JsonResult getEmployeeByNo(string EmpNo)
        {
            using (SampleDBangularEntities dataContext = new SampleDBangularEntities())
            {
                int no = Convert.ToInt32(EmpNo);
                var employeeList = dataContext.Employees.Find(no);
                return Json(employeeList, JsonRequestBehavior.AllowGet);
            }
        }

冷没有得到 Find 的定义

于 2020-10-19T12:20:18.917 回答
0

尝试这个。它将消除您的错误并且运行良好。

而不是使用DeleteObject方法尝试这个

Employee emp = new Employee();
foreach (int id in employeeIdsToDelete)
{
    emp = db.Employees.Find(id);
    db.Employees.Remove(emp);
    db.SaveChanges();
}
于 2016-04-14T15:53:22.920 回答