简体   繁体   English

将模型的检查功能放在何处(asp.net mvc5)

[英]where to put the checking function for the model (asp.net mvc5)

i know the model should not have any logic , but i don't know where is the good place to put the checking or the update function for a particular model 我知道模型不应该有任何逻辑,但是我不知道在哪里放置特定模型的检查或更新功能的好地方

ex. 例如

public class GuestBook
    {

        public int money { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        public string email { get; set; }
        public DateTime content { get; set; }
        public bool rich()
        {
            if (this.money <3000)
                return false;
            else
            return true;
        }
        public void earn(GuestBook b)
        {
            this.money += b.money;
        }
    }

the function rich() and earn() is only use for this module(GuestBook) if i didn't put it in this module , then where i should put? 如果我没有将rich()和earn()函数用于此模块(GuestBook),则应将其放在哪里?

Following good OOP design principles, the only way to really protect your classes' invariants (and not have a maintainability nightmare) is by not allowing them to be changed by anyone other than the class. 遵循良好的OOP设计原则,真正保护类的不变性(并且没有可维护性的噩梦)的唯一方法是不允许类以外的任何人更改它们。 Typically this is done by NOT exposing public setter methods ( public auto properties are evil ), making your fields readonly (wherever possible), and initializing them from the constructor. 通常,这是通过不公开公共设置方法( 公共自动属性是邪恶的 ),使字段为readonly (在可能的情况下)以及从构造函数初始化它们来完成的。

The whole point of having classes is to group data with behavior. 拥有类的全部目的是将数据与行为进行分组。 A simple data structure containing ints and strings is not a class in the OOP sense, it's just a struct. 从OOP角度来看,包含整数和字符串的简单数据结构不是类,而只是一个结构。

In some cases you are stuck with an even more evil ORM that FORCES you to make all properties public. 在某些情况下,您可能会遇到更加邪恶的ORM,该ORM迫使您将所有属性公开。 This is not an issue with Entity Framework (and some others too) though, EF can magically reflect in and access private setters if needed, you just gotta make sure there's also a private default constructor. 不过,这不是实体框架(以及其他一些实体)的问题,EF可以根据需要神奇地反映并访问私有设置程序,您只需确保还有一个私有默认构造函数即可。

According to your class rich method is validating and earn method is applying business logic. 根据您的班级, 丰富的方法在验证,而赚取方法在应用业务逻辑。 You can create AdditionalMetadataAttribute for rich method logic that can fire on ModelState.IsValid and for earn method you need to create BO class that apply your all business logic. 您可以为可以在ModelState.IsValid上触发的丰富方法逻辑创建AdditionalMetadataAttribute,并且需要为挣取方法创建应用所有业务逻辑的BO类。 here a link for AdditionalMetadataAttribute 这里是AdditionalMetadataAttribute的链接

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

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