开发者

How to have DataAnnotations persist down to ViewModels

In my application I have my Model structure decorated with DataAnnotations. This helps with my validation perfectly, however I'm not sure how to have those DataAnnotations persist down to my ViewM开发者_高级运维odels without double entry.

Basically I'm lazy, and I'm trying to keep it as DRY as possible.

class User
{
    [Required]
    public string FirstName {get; set; }
    [Required]
    public string LastName {get; set; }
    public datetime RegistrationDate {get; }
}

class CreateUserViewModel
{
    public string FirstName {get; set; }
    public string LastName {get; set; }    
}

The first class never gets used by the View, however it contains all of the DataAnnotations required by the application. The second class is always used by the CreateUser View, but I don't want to have to reapply the DataAnnotations. Is this possible? If so, how?


See the MetadataType attribute which will allow you to move the DataAnnotations to a separate class.


Maybe being lazy in this case isn't the best

Even though Todd provided a very nice approach by using metadata types I'm not sure I'd recommend them as the bulletproof solution.

Pro

  • it is true that you won't have to repeat validation attributes (especially if they configure localized error messages = even more code)

Con:

  • it's not immediately obvious on the model entity itself what is being validated
  • sometimes view models have the same property names, but their types differ hence validation logic can't be easily reused and you will end up with mixed validation approach in the same project which may be very confusing

Think of the complexity of your model entities and especially about the percentage of them that have a subset of properties of some other entity (in terms of types and names).

Maybe sometimes you must sacrifice some code to have cleaner and especially highly maintainable code. Mixing both makes it harder to maintain.


Try:

interface IAmALazyUser
{
    [Required]
    string FirstName {get; set; }
    [Required]
    string LastName {get; set; }
}

class User : IAmALazyUser
{
    public string FirstName {get; set; }
    public string LastName {get; set; }
    public datetime RegistrationDate {get; }
}

class CreateUserViewModel : IAmALazyUser
{
    public string FirstName {get; set; }
    public string LastName {get; set; }    
}

I wouldn't recommend it though since you add a coupling just to be able to not add validation to the view model.


I don't believe there is an easy solution to this. You will have to repeat yourself a little and annotate your view models too. If you are using the latest entity framework are your data tier then you can take advantage of the data validation using the annotated entity classes. so even if you forget to annotate a view model, when it gets to saving the data context will throw a validation exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜