Reputation: 47387
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 ViewModels 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?
Upvotes: 2
Views: 734
Reputation: 105029
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
Con:
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.
Upvotes: 3
Reputation: 3780
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.
Upvotes: 0
Reputation: 17272
See the MetadataType attribute which will allow you to move the DataAnnotations to a separate class.
Upvotes: 5
Reputation: 101150
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.
Upvotes: 1