r我需要一些关于在何处运行数据计算的建议。
我有一个 View 模型,其中包含我计算所需的所有字段,并且我为其中一个计算创建了以下内容:
public class CommissionVM
{
public int? LoanAmountLock { get; set; } // from loan table
public decimal BranchRev { get; set; } // from revenue table
public decimal BranchProcessFee { get; set; } // from revenue table
public decimal BranchGrossTotal
{
get
{
return Convert.ToDecimal(LoanAmountLock * (BranchRev/ 100) + BranchProcessFee);
}
}
我尝试在我的 View 中使用 Model.BranchGrossTotal,但它返回 0。我想我遇到了操作顺序问题。值 LoanAmountLock
、BranchRev
和 BranchProcessFee
作为查询结果返回:
public ActionResult Reconcile(int? id, string RevenueLoanType)
{
var model = new CommissionVM()
{
Loan = db.Loan.FirstOrDefault(a => a.id == id ),
BranchRevenues = db.BranchRevenues.FirstOrDefault(a => a.RevenueLoanType == RevenueLoanType),
};
return View(model);
}
在我用查询填充 View 模型之后,我最初能够通过在 Controller 中进行所有数学运算来使这些计算工作,但是大约会有 10 次计算,据我所知,我不应该弄乱我的业务逻辑 Controller 。
最好的解决方案是什么?我是否需要为计算创建另一个类?如果是这样,我如何用我的数据填充该类并在我的 Controller 中使用它?
编辑:我不确定如何设置业务类并在 Controller 中使用它们。谁能指出教程的方向?
最佳答案
您不应在 Controller 或 View 模型中进行计算。您应该在业务层中执行此操作。想想 View 模型是非常简单的类,其中包含要显示给用户的数据,仅此而已。
关于计算,您应该将其中一项转换为小数,而不是计算结果。如果你除以整数,你会得到一个整数。
例如,您可以创建一个类并将其命名为 CommissionService。该类应该调用您的数据层来获取数据,进行任何额外的计算并将数据(可能是 DTO)返回给 Controller 。 Controller 应基于 DTO 创建 View 模型并将它们发送到 View 。
阅读这些文章:
1) https://msdn.microsoft.com/en-us/library/hh404093.aspx
3) http://blog.diatomenterprises.com/asp-net-mvc-business-logic-as-a-separate-layer/
4) http://sampathloku.blogspot.com.ar/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html
关于c# - MVC - 数据计算最佳实践 - View 模型与 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730642/