简体   繁体   English

如何使用ASP.NET MVC中的实体框架在SQL Server中保存业务模型实体

[英]How to save a business model entity in SQL Server using Entity Framework in ASP.NET MVC

I have an entity class like this: 我有一个这样的实体类:

namespace Ozhay.Domain.Entities
{
    public class Cart
    {
        private List<CartLine> lineCollection = new List<CartLine>();

        public void AddItem(Product product, int quantity, string size, string color)
        {
            CartLine line = lineCollection
                .Where(p => p.Product.ProductID == product.ProductID)
                .FirstOrDefault();

            if (line == null)
            {
                lineCollection.Add(new CartLine { Product = product, Quantity = quantity, Size = size, Color = color });
            }
            else
            {
                line.Quantity += quantity;
            }
        }

        public void RemoveLine(Product product)
        {
            lineCollection.RemoveAll(l => l.Product.ProductID == product.ProductID);
        }

        public decimal ComputeTotalValue()
        {
            return lineCollection.Sum(e => e.Product.ProductPrice * e.Quantity);
        }

        public void Clear()
        {
            lineCollection.Clear();
        }

        public IEnumerable<CartLine> Lines
        {
            get { return lineCollection; }
        }

        public class CartLine
        {
            [Key]
            public int CartID { get; set; }

            [ForeignKey("Product")]
            public int ProductID { get; set; }
            public Product Product { get; set; }

            public int Quantity { get; set; }
            public string Size { get; set; }
            public string Color { get; set; }

        }
    }
}

I would like to save this into a SQL Server database table but the entity it self is very strange I can save an entity having properties but I have never used to save let say an operational entity, so what would be the right way to save the entity into the database. 我想将其保存到SQL Server数据库表中,但是它本身的实体很奇怪,我可以保存具有属性的实体,但是我从来没有用过保存,可以说一个操作性实体,那么保存该属性的正确方法是什么?实体进入数据库。

Here is the controller: 这是控制器:

public class CartController : Controller
{
        private IProductRepository repository;

        public CartController(IProductRepository repo)
        {
            repository = repo;
        }

        public ViewResult Index(Cart cart, string returnUrl)
        {
            return View(new CartIndexViewModel
            {
                ReturnUrl = returnUrl,
                Cart = cart,
            });
        }

        [HttpPost]
        public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl, string SelectedSizeText, string SelectedColorText, int SelectedQuantity)
        {
            Product product = repository.Products
                        .FirstOrDefault(p => p.ProductID == productId);

            if (product != null)
            {
                cart.AddItem(product, SelectedQuantity, SelectedSizeText, SelectedColorText);
            }

            return RedirectToAction("Index", new { returnUrl, SelectedSizeText, SelectedColorText });
        }

        public RedirectToRouteResult RemoveFromCart(Cart cart, int productId, string returnUrl)
        {
            Product product = repository.Products
                .FirstOrDefault(p => p.ProductID == productId);

            if (product != null)
            {
                cart.RemoveLine(product);
            }

            return RedirectToAction("Index", new { returnUrl });
        }

        public PartialViewResult Summary(Cart cart, string returnurl)
        {
            return PartialView(new CartIndexViewModel
            {
                ReturnUrl = returnurl,
                Cart = cart,
            });
        }

        private Cart GetCart()
        {
            Cart cart = (Cart)Session["Cart"];

            if (cart == null)
            {
                cart = new Cart();
                Session["Cart"] = cart;
            }

            return cart;
        }
}

For the moment it is being saved into asp.net session state. 目前,它正在保存为asp.net会话状态。

I propose you do not think about EF as about service that can save "business model entities". 我建议您不要将EF视为可以节省“业务模型实体”的服务。 EF is just data access layer that helps organize your code in ORM (object relation mapping) style. EF只是数据访问层,可帮助您以ORM(对象关系映射)样式组织代码。 Therefore you should be ready to operate RDBMS concepts (tables, FK, PK) otherwise you will be lost in abstraction leaks. 因此,您应该准备好操作RDBMS概念(表,FK,PK),否则您将迷失在抽象泄漏中。

In classical Magento shop, shopping cart is saved in quote table. 在经典的Magento商店中,购物车保存在报价表中。 How it is related with other tables could be examined there: 可以在这里检查它与其他表的关系:

https://anna.voelkl.at/wp-content/uploads/2016/12/ce2.1.3.png https://anna.voelkl.at/wp-content/uploads/2016/12/ce2.1.3.png

So I propose you to start thinking from "RDBMS point of view" even if you use "code first" approach you should use Entities design as a form to write DML ("Create Table ...") 因此,我建议您从“ RDBMS的观点”开始思考,即使您使用“代码优先”的方法,也应该使用实体设计作为编写DML的形式(“创建表...”)

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

相关问题 如何使用Entity Framework 6在ASP.NET MVC 5中保存自定义模型? - How to save custom model in ASP.NET MVC 5 with Entity Framework 6? 如何在Asp.net MVC 5中填充没有实体框架的模型 - How to populate a model without entity framework in Asp.net MVC 5 使用ASP.NET MVC中的Entity Framework将多张图片上传到SQL服务器数据库 - Upload multiple pictures to SQL Server database using Entity Framework in ASP.NET MVC 使用ASP.NET MVC中的Entity Framework将图片上传到SQL服务器数据库 - Upload picture to SQL Server database using Entity Framework in ASP.NET MVC 我如何使用实体框架ASP.NET MVC5保存相关数据? - How do i save related data using entity framework asp.net mvc5? ASP.NET MVC - 如何首先使用实体框架模型/数据库部署到 Azure? - ASP.NET MVC - How to Deploy to Azure using Entity Framework Model/Database First? 如何在不使用实体框架的情况下使用ASP NET MVC5从SQL Server显示表? - How to display table from SQL Server using ASP NET MVC5 without using Entity Framework? Asp.Net MVC 6实体框架-模型关系 - Asp.Net MVC 6 Entity Framework - Model relationships 如何仅通过添加ADO.NET实体数据模型ASP.NET MVC 3连接到SQL Server数据库和获取数据 - How to Connect to SQL Server Database and Fetch datas by Just adding ADO.NET Entity Data model ASP.NET MVC 3 ASP.NET 5 MVC 6和Entity Framework 7问题 - ASP.NET 5 MVC 6 and Entity Framework 7 issues
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM