3

I'm following the MusicStore tutorial I'm already on the Part 8 of the tutorial. I got this error when I tried to add the ShoppingCart class.. I tried to google for a possible solution but failed to find a clean one T_T .. based on my research I'm getting this error because I'm using edmx which is database first instead of code first on the tutorial.

I had this codes added and is having an error on Add() and 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();
        }
    }
}  

I'm a starter in MVC and hopefully anyone would help me to resolve this.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
bot
  • 4,841
  • 3
  • 42
  • 67
  • Please put the code of `ProjectEntities` class. – Pablo Claus Dec 19 '12 at 03:23
  • I'm sorry I'm doing it in database first so I only have the .emdx file on my Model folder which shows the relationship of tables. Under my .edmx file is Project.Designer.cs – bot Dec 19 '12 at 03:54

4 Answers4

4

OK here what I did guys to make it work.. instead of using .Add() I use .AddObject() and instead of using .Remove I use .DeleteObject().. I dont know the reason behind how this things work but atleast it doesn't show an error message anymore.. :P thanks for everyone who helped me.. :)

bot
  • 4,841
  • 3
  • 42
  • 67
  • 3
    The reason that worked is because you declared the Context using Object content and no DBContext. DBContext is wrapper on ObjectContext. Much easier to use. Somehow your exercise has mixed the 2 up. When creating the Model and Content in the place, if teh right project type is used and the Lastest nuget packages are in, you should get a T4 (template that generates code) that uses DBContext. The code you above is for accessing a context derived from DBContext. Suggest you take a close look at Your Context def and Regenerate it. Highly recommend that your move to DBcontext ;-) – phil soady Dec 19 '12 at 12:45
2

The add and remove are from EntityFrame namespace System.Data.Entity

so my guess is using System.Data.Entity missing ? Also check reference EntityFramework.dll added in project ? Or use package manager (nuget) to get EF added in project?, Does your context derive from DBContext ? If not No add. If you see AddObject, you are most likely deriving from ObjectContext instead

phil soady
  • 11,043
  • 5
  • 50
  • 95
  • I tried adding the reference using System.Data.Entity and also add the EntityFramework.dll on my project but still is not working.. T_T – bot Dec 19 '12 at 03:10
  • I closed my application and re-run it again but the error still appears.. T_T – bot Dec 19 '12 at 03:20
  • Did you accidentally hide the definition of DBSet? Intellisence shows what for Carts.? Im using these directives using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Objects; using System.Linq; using System.Linq.Expressions; using System.Data.Entity.Migrations; – phil soady Dec 19 '12 at 03:28
  • Sorry.. (I'm a little bit noob T_T) I dont know if I accidentally hide the definition of DBSet.. I'm using database first so all of the connections of my tables is in my database.. I'm just adding .edmx file to my Model as my reference.. – bot Dec 19 '12 at 03:45
  • Hard to say without access to project – phil soady Dec 19 '12 at 04:02
  • OK here what I did guys to make it work.. instead of using .Add() I use .AddObject() and instead of using .Remove I use .DeleteObject().. I dont know the reason behind how this things work but atleast it doesn't show an error message anymore.. :P thanks for anyone who help me.. I'll upvote everyone of you who tried to help me.. :) – bot Dec 19 '12 at 07:42
0

Try this. It will remove your error and works well .

Instead of using DeleteObject method try this one

Employee emp = new Employee();
foreach (int id in employeeIdsToDelete)
{
    emp = db.Employees.Find(id);
    db.Employees.Remove(emp);
    db.SaveChanges();
}
Ahmad
  • 5,551
  • 8
  • 41
  • 57
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);
            }
        }

Cold not get defination for Find