ASP上的计算值.NET核心与Angular应用程序



我目前正在ASP上开发一个应用程序。NET核心与Angular使用代码优先迁移和SQL Server。现在我有下面的";问题";。我有一些数据模型,其属性总是在任何更改时刷新。困难在于,它通常是基于其他模型的数据来计算的。

例如:

我有以下模型(这有点简化(:

public class Dinner {
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Recipe> recipes {get; set; }
public Dinner ()
{
Recipes= new Collection<Recipe>();
}
}
public class Recipe {
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Ingredient> ingredients {get; set; }
public Recipe ()
{
Ingredients = new Collection<Ingredient>();
}
}
public class Ingredient {
public int Id { get; set; }
public Product Product { get; set; }
public int ProductId { get; set; }
public Recipe Recipe { get; set; }
public int RecipeId { get; set; }
public decimal Quantity { get; set; }
}
public class Product {
public int Id { get; set; }
public string Name { get; set; }

public ICollection<Price> Prices { get; set; }
public Product()
{
Prices = new Collection<Price>();
}
}
public class Price {
public int Id { get; set; }
public decimal PricePerUnit { get; set; }
public Product Product { get; set; }
public int ProductId { get; set; }
}

我想要

  • 成分的计算属性(即基于产品价格的特定数量的价格(
  • 配方的计算属性(所有成分的所有成本之和(
  • 晚餐的计算属性(所有使用的食谱的总和(

我的问题是:对于最佳实践,我应该在哪里添加此属性?

目前,我通过计算onInit((过程中使用的接口的属性来计算应用程序组件上的这些属性。但这需要例如加载所有数据直到价格,以计算Dinner的sum属性。

我的目标是让这些sum属性尽可能更新,但我希望在SQL Server上进行计算(如果可能的话(,所以我确实需要加载更少的数据。这种方法有意义吗?我该如何实现这个目标?

您可以将计算添加为SQL Server中的计算列。在EF Core模型中,计算的列将被标记为这样。例如,当EF检索Dinner时,计算出的晚餐成本列将在SQL Server中进行计算,并返回给EF Core,而无需检索相关表。

查看模型,您的DB中似乎有三个表。

理想情况下,您应该将这些计算值存储在DB中。

这意味着,当你插入晚餐的记录时,你会先添加配料,然后计算所有配料的总和,然后插入食谱。同样,计算所有食谱的总数,并在添加晚餐时使用相同的食谱。所有这些计算都应该在控制器内部(准确地说是在存储库内部(进行。

然后,每当您阅读Dinner时,您都会将计算出的值从DB中获取到API中。

怎么说?

最新更新