简体   繁体   English

C#实体框架更好的功能或模型中的计算属性?

[英]C# entity framework better function or calculated property in model?

Hello I'm writing a little C# web app using asp.net core 1.1 MVC with EF (code first) 您好,我正在使用带有EF的asp.net core 1.1 MVC编写一个小的C#Web应用程序(代码优先)

I want to know what is the best engineering choice. 我想知道什么是最佳的工程选择。 Let's assume that I have a class and I need to calculate something using one or more related properties; 假设我有一个类,并且需要使用一个或多个相关属性来计算某些内容; let's make an example: 让我们举个例子:

class A
{
    public virtual int Id { get; set; }
    public virtual Collection<B> Bs { get; set; }    

    public int GetMaxB()
    {
        return Bs.Max( b => b.Num ); /*simple example, can be more complex */
    }
}

class B
{    
   public virtual int Id { get; set; }
   public virtual int Num { get; set; } 
}

So, for GetMaxB() (let's think about a more complex function, not only one line) what is the best option? 那么,对于GetMaxB() (让我们考虑一个更复杂的函数,而不仅仅是一行),最佳选择是什么?

  • a function in the model class 模型类中的函数
  • a generated (NotMapped) property in the model class 模型类中生成的(NotMapped)属性
  • a function in controller 控制器中的功能
  • other 其他

您的逻辑可以是VM的一部分,您可能不希望将其与Model混合使用,而Model应该是具有属性的纯类。

Depends upon situations and nature of property. 取决于情况和财产的性质。

A calculated property like DiscountValue (which depend few other properties) be part of Model class. 诸如DiscountValue的计算属性(依赖于其他几个属性)是Model类的一部分。

If use of a GetMaxB() is less frequent then it can be a function in Model. 如果使用GetMaxB()的频率较低,那么它可以是Model中的函数。

If GetMaxB() is only reason for which collection class is used in Class A, then you can think separate out provided use is not frequent. 如果GetMaxB()仅是在类A中使用集合类的原因,那么您可以认为分开使用是不常见的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM