假设我有这个模型
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
}
有人可以解释一下,将这些物品放入购物车并下订单的最简单方法是什么?
有很多方法可以实现你的目标。 这里有一种方法:
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
}
public class CartItem
{
public Book Book { get; set;}
public int Quantity { get; set;}
}
public class Order
{
public List<CartItem> CartItems { get; set;}
public int OrderNumber { get; set;}
public decimal OrderTotal { get; set;}
}
然后,您可以将书籍添加到订单中包含的购物车(购物车List<CartItems>
(。
要进行演示,请考虑:
var book = new Book{ Id = 123, Title = "Hello World", Price = 42.42M };
var cartItem = new CartItem{ Book = book, Quantity = 2 };
var order = new Order{OrderNumber = 66};
order.CartItems = new List<CartItem>();
order.CartItems.Add(cartItem);
Console.WriteLine();
foreach(var item in order.CartItems)
{
Console.WriteLine("Book ID: " + item.Book.Id);
Console.WriteLine("Book Title: " + item.Book.Title);
Console.WriteLine("Book Price: " + item.Book.Price);
Console.WriteLine("Quantity: " + item.Quantity);
Console.WriteLine("SubTotal: " + item.Quantity * item.Book.Price);
order.OrderTotal += item.Quantity * item.Book.Price;
}
Console.WriteLine("Order Total: " + order.OrderTotal);
演示:https://dotnetfiddle.net/qpi1ku