我有一个
OrderBookItem
模型。
我需要添加列TotalPrice
。本栏按照公式TotalPrice = Book.Price * Quantity
计算。我不知道如何正确地做到这一点。需要你的帮助。
public class OrderBookItem
{
[Key]
public int Id { get; set; }
[Required]
public int OrderId { get; set; }
[ForeignKey("OrderId")]
public Order Order { get; set; }
[Required]
public int BookId { get; set; }
[ForeignKey("BookId")]
public Book Book { get; set; }
[Required]
public int Quantity { get; set; }
public decimal TotalPrice { get; set; }
// need to calculate this property by formula `Book.Price * Quantity`
}
public class OrderBookItemDTO
{
public int BookId { get; set; }
public int Quantity { get; set; }
}
据我了解,当将
BookId
传递给DTO模型然后映射它时,EF Core应该自动在BookId
和Book
之间建立连接。如果我说错了请指正
我尝试了很多变体。但没有任何帮助我
getter 和 setter 应该为此工作。
在
TotalPrice
属性中,应该能够使用 getter 和 setter 来计算该值。添加一个可以存储该值并返回该值的私有字段。就叫它totalPrice
。
private decimal totalPrice;
public decimal TotalPrice
{
get { return totalPrice; }
set { totalPrice = Book.Price * Quantity; }
}