I have the following domain entity:
public class CartItem
{
public virtual Guid Id { get; set; }
public virtual Guid SessionId { get; set; }
public virtual int Quantity { get; set; }
public virtual Product Product { get; set; }
}
I have the following DTO:
public class CartItemDTO
{
public CartItemDTO(CartItem cartItem)
{
Id = cartItem.Id;
Quantity = cartItem.Quantity;
Name = cartItem.Product.Name;
Price = cartItem.Product.Price;
}
public Guid Id { get; private set; }
public int Quantity { get; private set; }
public string Name { get; private set; }
public decimal Price { get; private set; }
}
The current work flow is pretty simple: my repository returns a IEnumerable of type CartItem. My service transforms it to dto's (CartItemDTO). My controller then passes it to the view. So far so good.
Now I want to implement a total for each of the line items. I added the following property to CartItemDTO.
public decimal Total { get; private set; }
I then added the following code to the CartItemDTO constructor.
Total = cartItem.Quantity * cartItem.Product.Price;
My first question is if this is a best practices approach? If not, why? Should I have added the Total property somewhere else? If so, why?
I also wanted to implement a total for the entire cart so I create a new class (below) and modified my service to return it.
public class CartItemResult
{
public CartItemResult(IEnumerable<CartItemDTO> result)
{
CartItems = new List<CartItemDTO>(result);
Total = result.Sum(total => total.Total);
}
public IList<CartItemDTO> CartItems { get; private set; }
public decimal Total { get; private set; }
}
I could now either pass the new class to the view or create a separate ViewModel and pass the content of the new class to the ViewModel and pass that to the view.
My second question is, again if this approach is a best practices approach? If not, why and what should I have done differently?