EF中无需关联对象,如何获取已存储的计算属性?
从Dapper迁移至EF:查询Invoice实体直接获取Total计算属性的问题
我正将数据库持久化方案从Dapper迁移至EF。目前,我需要获取Invoice类中已存储在数据库的Total计算属性,但必须通过关联/包含InvoiceItem等相关对象才能实现。请问是否可以仅查询Invoice实体即可获取该Total属性?
示例代码
public class Invoice{ private decimal _total=0; public IEnumerable<InvoiceItem> Items{get;set;} public decimal Total{ get=> Items.Sum(x=>x.Total); private set=> _total=value; } } public class InvoiceItem{ public decimal Total{get;set;} }
补充:实际项目中的Invoice实体代码
实际项目中,Total属性依赖多张表关联计算得出:
public class Invoice{ //other properties public decimal Total{ get => CalculateTotal(); set => _ = value; } private decimal CalculateTotal() { var previousStatementTotal = PreviousStatement?.Total ?? 0; var miscChargeTotal = LeaseMiscellaneousChargeInvoice?.Total ?? 0; return previousStatementTotal+ RentsInvoice.Sum(x => x.Total) + RentsInvoice.Sum(x => x.ValueAddedTaxAfterDiscount) + RentsInvoice.Sum(x => x.WitholdingTaxAfterDiscount) + miscChargeTotal+ Utilities.Sum(x => x.Total) + Utilities.Sum(x => x.ValueAddedTaxAfterDiscount) + DeductionInvoices.Sum(x => x.Amount) + OtherCharges.Sum(x => x.Total); } }
问题解决情况
我已采用@Steve-Py的建议,问题已解决。
内容的提问来源于stack exchange,提问作者forgetaboutme
相关产品推荐
相关产品推荐

