System.InvalidOperationException:'实体类型CartItem不是当前上下文模型的一部分。'

时间:2018-07-06 10:59:51

标签: c# asp.net .net model-view-controller

我刚开始使用asp.net mvc。我想添加服务车。我有用sql脚本编写的该项目的数据库,例如:

Create table [Laundries].[CartItems](
[Id]                        BIGINT      IDENTITY (1, 1) NOT NULL,
[CartId]                    BIGINT                      NOT NULL,
[Price]                     FLOAT                       NOT NULL,
[ServiceId]                 BIGINT                      NOT NULL,
[UserId]                    BIGINT                      NULL,
[Quantity]                  BIGINT                      NOT NULL,

    CONSTRAINT [PK_Laundries.Carts] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_Laundries.Services] FOREIGN KEY([ServiceId])
    REFERENCES [Laundries].[Services]([Id]),
    CONSTRAINT [FK_Laundries.Carts1] FOREIGN KEY([UserId])
    REFERENCES [Core].[Users]([Id]),

);

我有购物车服务

    using Ideo.Mvc.Data.Model;
using Ideo.Mvc.Data.Model.Core;
using Ideo.Mvc.Data.Model.Laundries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Ideo.Mvc.Data.Services.Core
{
    public partial class ShoppingCart
    {
        long? ShoppingCartId { get; set; }

        public const string CartSessionKey = "CartId";


        #region GetCart()
        public static List<CartItem> GetCart(long? userId)
        {
            List<CartItem> listOfItemsInCart;
            using (var context = Context.Read())
            {
                listOfItemsInCart = context.Query<CartItem>().
                Where
                (
                p => p.UserId == userId).
                ToList()
                ;
            }

            return listOfItemsInCart;

        }

        #endregion


        #region GetList()

        public static IEnumerable<TResult> GetList<TResult>(IPager pager, long? cartId = null, int? quantity = null,  long? serviceId = null)
        {
            using (var context = Context.Read())
            {
                var query = context.Query<CartItem>().AsQueryable();

                if (cartId != null)
                {
                    query = query.Where(p => p.CartId.Equals(cartId));
                }
                if (quantity != null)
                {
                    query = query.Where(p => p.Quantity.Equals(quantity));
                }
                if (quantity != null)
                {
                    query = query.Where(p => p.Quantity.Equals(quantity));
                }

                if (serviceId != null)
                {
                    query = query.Where(p => p.ServiceId.Equals(serviceId));
                }
                //query = query.Where(p => p.IsActive == true && p.IsVerified == true);
                return query
                    .Pager(pager)
                    .GetResult<TResult>();
            }
        }
        #endregion

        //public static ShoppingCart GetCart()
        //{
        //    // redirect
        //}

        #region AddToCart()
        public void AddToCart(Service service)//
        {
            CartItem cartItem;
            using (var context = Context.Read())
            {
                cartItem = context.Query<CartItem>().
                SingleOrDefault(
                p => p.CartId == ShoppingCartId
                && p.ServiceId == service.Id);//
            }
            if (cartItem == null)
            {
                cartItem = new CartItem
                {
                    ServiceId = service.Id,
                    CartId = ShoppingCartId,
                    Quantity = 1,
                };
                using (var context = Context.Write())
                {
                    context.Create(cartItem);
                    context.SaveChanges();
                }
            }
        }


        #endregion

        public int RemoveFromCart(long id)
        {
            CartItem cartItem;
            using (var context = Context.Read())
            {
                cartItem = context.Query<CartItem>().
                Single(
                p => p.CartId == ShoppingCartId
                && p.ServiceId == id);
            }
            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.Quantity > 1)
                {
                    cartItem.Quantity--;
                    itemCount = cartItem.Quantity;
                    using (var context = Context.Write())
                    {
                        context.Update(cartItem);
                        context.SaveChanges();
                    }
                }
                else
                {
                    using (var context = Context.Write())
                    {
                        context.Delete(cartItem);
                        context.SaveChanges();
                    }
                }
            }
            return itemCount;
        }

        public void EmptyCart()
        {
            List<CartItem> cartItems;
            using (var context = Context.Read())
            {
                cartItems = context.Query<CartItem>().
                Where(
                p => p.CartId == ShoppingCartId).
                ToList();
            }
            foreach (var cartItem in cartItems)
            {
                using (var context = Context.Write())
                {
                    context.Delete(cartItem);
                    context.SaveChanges();
                }
            }
        }


        public List<CartItem> GetCartItems()
        {
            List<CartItem> cartItems;
            using (var context = Context.Read())
            {
                cartItems = context.Query<CartItem>().
                Where(
                p => p.Id == ShoppingCartId).
                ToList();
            }
            return cartItems;
        }

        public int GetCount()
        {
            int? count;

            using (var context = Context.Read())
            {
                count = context.Query<CartItem>().
                Where(
                p => p.Id == ShoppingCartId).
                Select(p => p.Quantity).
                Sum();
            }
            return count ?? 0;
        }

        public double GetTotal()
        {
            float? total;
            using (var context = Context.Read())
            {
                total = context.Query<CartItem>().
                    Where(
                    p => p.Id == ShoppingCartId).
                    Select(p => p.Quantity * p.Service.ServicePrice).Cast<float?>()
                    .Sum();
            }
            return total ?? 0;

        }



        public long CreateOrder(Orders order)
        {
            double? orderTotal = 0;
            var cartItems = GetCartItems();
            foreach (var item in cartItems)
            {
                var orderDetail = new OrdersDetalis
                {
                    ServiceId = item.ServiceId,
                    OrderId = order.Id,
                    NetPrice = item.Service.ServicePrice,
                    GrossPrice = (item.Service.ServicePrice * 1.23),
                    Quantity = item.Quantity
                };
                orderTotal += item.Quantity * item.Service.ServicePrice;

                using (var context = Context.Write())
                {
                    context.Create(orderDetail);
                    context.SaveChanges();
                }
            }

            order.SumNetPrice = orderTotal;
            order.OrderDateUtc = DateTime.Now;
            order.StatusId = 1;
            //TODO wyliczanie kolejnego zamówienia
            order.OrderNumber = Convert.ToString(DateTime.Now.Year) + "/" + order.Laundry + "/" + 1;

            using (var context = Context.Write())
            {
                context.Create(order);
                context.SaveChanges();
            }
            EmptyCart();
            return order.Id;
        }

        public long? GetCartId(long? userId)
        {

            long? cartId;
            using (var context = Context.Read())
            {
                var query = context.Query<CartItem>().AsQueryable();

                query = query.Where(p => p.UserId == userId);
                cartId = query.FirstOrDefault().Id;

            }

            return cartId;
        }
        // When a user has logged in, migrate their shopping cart to
        // be associated with their username
        //public void MigrateCart(long userId)
        //{
        //    List<CartItem> shoppingCart;
        //    //ShoppingCartService shoppingCart;
        //    using (var context = Context.Read())
        //    {
        //        var query = context.Query<CartItem>().AsQueryable();

        //        query = query.Where(p => p.UserId == UserId);
        //        query = query.Where(p => p.CityId == CityId);

        //        return query.FirstOrDefault();
        //    }
        //    foreach (Cart item in shoppingCart)
        //    {
        //        item.CartId = userName;
        //    }
        //    storeDB.SaveChanges();
        //}
    }
}

和控制器

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ideo.Mvc.Data.Model.Core;
using Ideo.Mvc.Data.Services.Core;
using Microsoft.AspNet.Identity;
using Ideo.Mvc.Data.Model.Laundries;
using Ideo.Mvc.Web.Areas.Default.Models.Carts;

namespace Ideo.Mvc.Web.Areas.Default.Controllers
{
    public partial class ShoppingCartController : Controller
    {

        public virtual ActionResult Index()
        {
            var userID = Convert.ToInt64(User.Identity.GetUserId());
            var viewModel = new ShoppingCartViewModel
            {
                CartItems = ShoppingCart.GetCart(userID),

            };
            return View(viewModel);
        }
        //[HttpPost]
        //[ActionName("List")]
        //[ValidateAntiForgeryToken]
        //#region List()
        //public virtual ActionResult List(ShoppingCartDataSource dataSource)
        //{
        //    dataSource.Data = ShoppingCart.GetList<CartListViewModel>(
        //        dataSource,
        //        dataSource.CartId,
        //        dataSource.Quantity,
        //        dataSource.DateCreated,
        //        dataSource.UserId

        //        );
        //    return View(MVC.Default.ShoppingCart.Views.ViewNames.List, dataSource);


        //}

        //#endregion
        public virtual ActionResult AddToCart(Service service)
        {
            var userID = Convert.ToInt64(User.Identity.GetUserId());
            var cart = ShoppingCart.GetCart(userID);
            ShoppingCart.AddToCart(service);
            return RedirectToAction("Index");
        }

        [HttpPost]
        public virtual ActionResult RemoveFromCart(long id)
        {
            var userID = Convert.ToInt64(User.Identity.GetUserId());

            var cart = ShoppingCart.GetCart(userID);


            string serviceName = "andrzej";//TODO getServiceNameById(id)

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

            // Display the confirmation message
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(serviceName) +
                    "[[[ zotał usunięty z twojego koszyka]]]",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };
            return Json(results);
        }
        //
       // [HttpPost]
        // GET: /ShoppingCart/CartSummary
        //[ChildActionOnly]
        public virtual ActionResult CartSummary()
        {
            long? userID = Convert.ToInt64(User.Identity.GetUserId());
            var cart = ShoppingCart.GetCart(userID);

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

        //[HttpPost]
        //public virtual ActionResult CreateOrder()
        //{
        //    var userID = Convert.ToInt64(User.Identity.GetUserId());
        //    var cart = ShoppingCart.GetCart(userID);


        //}
    }
}

我知道它搞砸了 我想再次重写它,但我不明白我何时进入shoopingcart / index,但出现标题为“实体类型CartItem不属于当前上下文模型的一部分”之类的错误

这是购物车中所有物品的购物视图。这是基本的。我必须在此视图上工作,但首先我需要对控制器/服务进行排序。     @using Ideo.Mvc.Web.Areas.Default.Models     @model CmpnyMessageDataSource

@foreach (var message in Model.Data)
{
    using (var p = Html.Bootstrap().Begin(new Panel()))
    {

        @p.Heading(@message.Date.ToString("g"));

        using (p.BeginBody())
        {
            <p>@message.Content</p>
        }

        // @p.Footer()
    }
}

0 个答案:

没有答案