【发布时间】:2017-05-29 13:09:15
【问题描述】:
我有两个课程Invoice 和InvoiceProducts。 InvoiceProducts 是一个集合,有一个名为 Price 的仅获取属性,我希望 Invoice 有一个名为 TotalPrice 的属性,它将返回添加到它的 InvoiceProducts 集合中的 Price foreach 项目。但是,我不确定是否要这样做。以我尝试使用的当前方式,我收到一条错误消息
“对象引用未设置为对象的实例。”有没有办法做到这一点?
目前的方式:
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; }
}
【问题讨论】:
-
为 InvoiceProducts 添加初始化(例如 public virtual ICollection
InvoiceProducts { get; set; } = new List ();) -
你也可以删除TotalPrice的set部分,只使用get(当然是在return之前计算答案)
标签: c# entity-framework asp.net-mvc-5