Where to place the Data Annotations?

0

Just in case there is a problem with concepts, I define:

Model: = The class that establishes the Tables of the database.

ViewModel: = The class I use to send to the Views (so as not to pass the complete Model).

My question is this:

To establish the KEY or to indicate that it is a possible unique value in the database, I have to put the corresponding Data Annotations in the Model.

But to establish that a property is mandatory or that it can not be equal to 0 for example, do I put the corresponding Data Annotation in the ViewModel only? Or do I have to put both in the Model and in the ViewModel?

It is assumed that in the View the data is loaded in the ViewModel, therefore it is in the ViewModel where the Data Annotation should be with their respective Error messages.

Am I right?

    
asked by Edu 15.11.2018 в 22:41
source

1 answer

2

The Data Annotations you must define them in the properties that are part of the binding of controls that you want to validate, if you are bindeando the Model to textbox and you want to indicate that they are obligatory you should put the [Required] to indicate it

Now, what I notice is that you confuse the attributes of entity framework with those you use in the validation, when you define [Key] this is not Data Annotations but entity framework , the problem is that you use the same class in view and in persistencia , I do not say that this bad is that now much code, but the advisable thing is that they are different classes

If you have a Persona class that you would use with entity framework and another class PersonaModel that you would use with mvvm to represent the data in the view, this way if you use attributes the persistence ones will be separated from those of visualization, the idea is to convert from one to another, you can use linq or the library automapper to help you

    
answered by 15.11.2018 в 23:00