Model多增加兩隻class在C#專案
public class ShoppingCart
{
public int Id { get; set; }
public Guid SessionId { get; set; }
public DateTime CreatedOn { get; set; }
public List<CartLineItem> Items { get; set; } = new List<CartLineItem>();
}
public class CartLineItem
{
public int Id { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
}
資料庫上下文添加ShoppingCart的Entity
public class StoreContext : DbContext
{
public StoreContext(DbContextOptions<StoreContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
public DbSet<ShoppingCart> ShoppingCart { get; set; }
}
新增好Cart控制器
[Route("api/[controller]")]
[ApiController]
public class CartController : ControllerBase
{
private readonly StoreContext dbContext;
public CartController(StoreContext dbContext)
{
this.dbContext = dbContext;
}
[HttpPost]
public IActionResult AddItem(AddItemCommand command)
{
var cart = new ShoppingCart { SessionId = Guid.NewGuid(), CreatedOn = DateTime.Now };
cart.Items.Add(new CartLineItem { ProductId = command.ProductId, Quantity = 1 });
dbContext.ShoppingCart.Add(cart);
dbContext.SaveChanges();
return Ok();
}
}
public class AddItemCommand
{
public int ProductId { get; set; }
}