计算栏包含外国财产

问题描述 投票:0回答:1

我有一个

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
之间建立连接。如果我说错了请指正

我尝试了很多变体。但没有任何帮助我

c# asp.net-core entity-framework-core
1个回答
0
投票

getter 和 setter 应该为此工作。

TotalPrice
属性中,应该能够使用 getter 和 setter 来计算该值。添加一个可以存储该值并返回该值的私有字段。就叫它
totalPrice

private decimal totalPrice;

public decimal TotalPrice
{
    get { return totalPrice; }
    set { totalPrice = Book.Price * Quantity; }
}
© www.soinside.com 2019 - 2024. All rights reserved.