I have two classes Invoice and InvoiceProducts. InvoiceProducts is a collection and has a get only property called Price and I want Invoice to have a property called TotalPrice which would return the Price foreach item in the InvoiceProducts collections added to it. However I'm not sure about going about this. With the current way I'm trying to use it I get an error saying
"Object reference not set to an instance of an object." Is there a way to do this?
Current way:
public class Invoice
{
public int InvoiceID { get; set; }
public string ClientName { get; set; }
public DateTime Date { get; set; } = DateTime.Today;
private decimal totalPrice;
public decimal TotalPrice {
get
{
return totalPrice;
}
set
{
foreach(var item in InvoiceProducts)
{
totalPrice += item.Price;
}
}
}
public virtual ICollection<InvoiceProducts> InvoiceProducts { get; set; }
}
public class InvoiceProducts
{
public int InvoiceProductsID { get; set; }
public int InvoiceID { get; set; }
public int ProductID { get; set; }
public int ProductQuantity { get; set; }
public decimal Price { get { return Product.ProductPrice * ProductQuantity; } }
public virtual Invoice Invoice { get; set; }
public virtual Product Product { get; set; }
}