使用 Angular App 在 ASP.NET Core 上计算的值

问题描述

我目前正在使用 Code First Migration 和 sql Server 在带有 Angular 的 ASP.NET Core 上开发应用程序。现在我有以下“问题”。我有具有属性的数据模型,这些属性总是在任何更改时刷新。难点在于往往是根据其他模型的数据计算出来的。

举个例子:

我有这些模型(简化了一点):

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 上进行计算(如果可能),因此我确实需要加载更少的数据。这种方法有意义吗?我怎样才能实现这个目标?

解决方法

查看模型,您的数据库中似乎有三个表。

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

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

然后,每当您阅读 Dinner 时,您都会将 DB 中的计算值输入到您的 API 中。

怎么说?

,

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