简体   繁体   English

如何使用asp.net + MVC在数据库中保存购物车的会话值

[英]How to save session values of shopping cart in database using asp.net + MVC

So this is my code for add to cart.所以这是我添加到购物车的代码。 Now i wish to save the session objects in database.现在我希望将会话对象保存在数据库中。 Can someone explain to me how should i proceed with it有人可以向我解释我应该如何进行

public ActionResult Cart(int id)
    {
        if (Session["cart"] == null)
        {
            var cart = new List<Item>();              
            cart.Add(new Item(_productService.GetProductById(id), 1));
            Session["cart"] = cart;
        }
        else
        {
            var cart = (List<Item>)Session["cart"];
            int index = isExisting(id);
            if (index == -1)
            {
                cart.Add(new Item(_productService.GetProductById(id), 1));
            }
            else
            {
                cart[index].Quantity++;
            }
            Session["cart"] = cart;
        }
        var userModel = new UserViewModel(true, null, null);
        return View(userModel);
    }

There are several methods to save data to a databbase via ASP.NET.有几种方法可以通过 ASP.NET 将数据保存到数据库。

I recommend you look into using an Object-Relational Mapping tool:我建议您考虑使用对象关系映射工具:

  1. NHibernate (with FluentNHibernate) NHibernate(使用 FluentNHibernate)
  2. EntityFramework实体框架

There is a plethora of documentation resources for each of these tools.每个工具都有大量的文档资源。

You can also resort to using ADO.NET, but this is not recommended unless you absolutely have to use it.您也可以使用 ADO.NET,但不建议这样做,除非您绝对必须使用它。

I deal with this exact scenario.我处理这个确切的场景。 One option is to serialize your cart as XML and store the XML in a database column.一种选择是将您的购物车序列化为 XML 并将 XML 存储在数据库列中。 This approach is useful if you don't expect that you'll need to query the specifics of the object - you just want to save and restore it, which is what you're doing with Session.如果您不希望需要查询对象的详细信息,则此方法很有用 - 您只想保存和恢复它,这就是您对 Session 所做的。 The downside is that you could lose some backwards compatibility if you modify the class or classes that make up a cart.缺点是如果您修改构成购物车的一个或多个类,您可能会失去一些向后兼容性。

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

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