I am working on an ASP.NET MVC 2 project with some business objects that apply data metadata data attributes (validation attributes, display attributes, etc.) to them.
Sort of:
//User entity public class User { [DisplayName("Vorname")] [Required(ErrorMessage = "Vorname fehlt")] [StringLength(MaxNameLength, ErrorMessage = "Vorname ist zu lang")] public string FirstName { get; set; } [DisplayName("Nachname")] [Required(ErrorMessage = "Nachnamefehlt")] [StringLength(MaxNameLength, ErrorMessage = "Nachname ist zu lang")] public string LastName { get; set; } [Required] public string Password{ get; set; } }
Using metadata from different views is not a problem if I use my business entities as view modes or as part of such a view model:
However, sometimes I need to encode a view to edit some, but not all fields of an object. For these fields, I want to reuse the metadata already specified in my user entity. The remaining fields should be ignored. I am talking about custom view models, such as:
[MetadataType(typeof(User))] public class UserNameViewModel { public string FirstName { get; set; } public string LastName { get; set; }
Where I ran into problems. The user view model above throws an exception when a view is created because it does not have a password property.
The associated metadata type for the type 'Zeiterfassung.Models.ViewModels.Users.UserNameViewModel + UserModel' contains the following unknown properties or fields: Password. Please make sure that the names of these members match the names of the properties on the main type.
In addition, even if this exception did not occur, I expect to get even more problems with checking the model when submitting the form, because the Password is marked as required in my business entity.
I can come up with a few workarounds, but no one seems really perfect. In any case, I cannot change the database layout so that the password field is in a separate object in my example above.
How would you handle this scenario?