音乐商店 'System.Data.Objects.ObjectSet<....>' 不包含 'Add' 的定义,也没有接受第一个参数的扩展方法 'Add' 。

3
我正在跟随MusicStore教程,已经到了教程第八部分。当我尝试添加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的初学者,希望有人能帮助我解决这个问题。


请放置 ProjectEntities 类的代码。 - Pablo Claus
抱歉,我正在使用数据库优先模式进行操作,因此我的Model文件夹中只有.emdx文件,该文件显示了表之间的关系。在我的.edmx文件下面是Project.Designer.cs文件。 - bot
4个回答

4

好的,这里是我做的事情,让它工作起来...我使用了.AddObject()而不是使用.Add(),并且使用了.DeleteObject()而不是使用.Remove()...我不知道这些东西背后的原因,但至少不再显示错误消息了.. :P 感谢所有帮助过我的人.. :)


3
工作正常的原因是因为您使用了Object content而不是DBContext来声明Context。DBContext是ObjectContext的包装器,更易于使用。但是某种方式,在您的练习中将两者混淆了。如果在创建模型和内容时使用了正确的项目类型并且最新的nuget包已经安装,那么您应该会得到一个使用DBContext的T4(生成代码的模板)。上面的代码用于访问派生自DBContext的上下文。建议您仔细查看您的上下文定义并重新生成它。强烈建议您转移到DBContext。;-) - phil soady

2

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

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


我尝试使用System.Data.Entity添加引用,并在我的项目中添加了EntityFramework.dll,但仍然无法正常工作.. T_T - bot
我关闭了应用程序并重新运行,但错误仍然出现...T_T - bot
你不小心隐藏了DBSet的定义吗?Intellisence为Carts显示了什么?我正在使用以下指令: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
抱歉..(我有点新手T_T)我不知道是否意外隐藏了DBSet的定义..我正在使用数据库优先,因此我的所有表的连接都在我的数据库中..我只是将.edmx文件添加到我的模型作为参考.. - bot
没有项目访问权限,很难说。 - phil soady
好的,这是我做的,让它工作起来...不使用 .Add(),而是使用 .AddObject(),不使用 .Remove,而是使用 .DeleteObject()。我不知道这些东西背后的原因,但至少不再显示错误消息了... :P 感谢所有帮助我的人...我会给每个尝试帮助我的人点赞... :) - bot

0

试试这个。它会消除你的错误并且运行良好。

不要使用DeleteObject方法,尝试使用这个方法。

Employee emp = new Employee();
foreach (int id in employeeIdsToDelete)
{
    emp = db.Employees.Find(id);
    db.Employees.Remove(emp);
    db.SaveChanges();
}

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的定义


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接