Where to put Data Annotation? View Model or Model?

Asked

Viewed 339 times

8

Using Entity Framework Code First, with view model and model.

To create a column with varchar(2), need to put the MaxLength(2) in the model and in the view model?

  • if you are using Entity Framework Code First, then you are probably creating your domain classes (in the case of your Models) that EF will map to the database: a good and great shape that I use a lot is the Specifications standard. if you want I prepare a good answer with an example.

2 answers

8


Not

Viewmodels do not serve to create entities in a bank. [MaxLength] serves precisely to specify the width of the column in bench. Therefore, [MaxLength] should be used only in Model.

To Viewmodels, use [StringLength].

  • If for some reason I have to change in 2 to 4, I’ll have to change in both places?

  • Or when I create my View Model it will assume the "rules" of Model?

  • Yeah, you’re gonna have to change both.

2

Depends on how you want to secure it. It seems to me that you want to ensure under all circumstances that this property and consequently the database column has 2 characters at most. So put in the model. It is he who is worth the whole application.

If you use view model, use it if you want only in this circumstance the validation is used. Obviously if there is conflict between the two, if all is correct, the model must prevail.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.