I have DTOs that are mapped to ViewModels. To avoid having to manage validation attributes (and other attributes), I wanted to write the validation attributes for all the properties on a single class and reuse it on my ViewModels. However, when I try to use the Metadata on a ViewModel that does not have all the properties of the DTO (all of them really...), it gives me an System.InvalidOperationException
exception.
Exception:
Le type de métadonnées associé pour le type 'MyProject.EntityViewModel' contient les propriétés ou champs inconnus suivants : AnotherProperty. Vérifiez que les noms de ces membres correspondent aux noms des propriétés du type principal.
Google translated:
The type associated metadata for type 'MyProject.EntityViewModel' contains the following unknown properties or fields: AnotherProperty. Verify that the names of these members match the names of the properties of the main type.
Simplified example:
public class Entity {
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
public class EntityDTO {
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
//This class is used to add validation attributes for input-related view models
public class EntityInputValidation {
[Required]
public string A { get; set; }
[Required]
public string B { get; set; }
//Notice that we dont have a validation for C
}
//This class is a ViewModel used to create a new Entity
[MetadataType(typeof(EntityInputValidation))]
public class EntityCreateViewModel {
//Required because we use the InputValidation metadata
public string A { get; set; }
//Notice that we do not have the B property here, even if we are using the Input Validation which has a required attribute for this property. This is where the exception comes from.
//C is only required in this View/ViewModel
[Required]
public string C { get; set; }
}
Because EntityViewModel does not have AnotherProperty
, it will throw an exception. Is there a way to prevent this?