【问题标题】:Calculated values on a ASP.NET Core with Angular App带有 Angular 应用程序的 ASP.NET Core 上的计算值
【发布时间】:2021-07-24 15:22:16
【问题描述】:

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

举个例子:

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

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

【问题讨论】:

    标签: c# sql-server angular entity-framework-core ef-code-first


    【解决方案1】:

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

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

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

    然后,每当您阅读晚餐时,您都会将数据库中的计算值获取到您的 API 中。

    怎么说?

    【讨论】:

    • 我将首先尝试使用另一篇文章中提到的计算列。但也感谢您的反馈和想法。
    【解决方案2】:

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

    【讨论】:

    • 谢谢。我会尝试一下我的解决方案。如果可行,我会将其标记为答案。
    猜你喜欢
    • 2022-11-05
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2019-10-01
    相关资源
    最近更新 更多