I have a model with certain properties. I use a separated class with the MetadataType to define requirements for properties. I also try to use the same metadata class with a viewmodel defining just a subset of properties. This is a simple example code of the situation for clarification:
[MetadataType(typeof(Metadata))]
class ModelA
{
public class Metadata
{
[Required]
public object Property1 { get; set; }
[Required]
public object Property2 { get; set; }
}
public int Property1 { get; set; }
public int Property2 { get; set; }
}
[MetadataType(typeof(ModelA.Metadata))]
class ViewModelA
{
public int Property1 { get; set; }
}
The problem is when the razor engine tries to process the view, it throws the an InvalidOperationException with the following error message:
The associated metadata type for type 'ViewModelA' contains the following unknown properties or fields: Property2. Please make sure that the names of these members match the names of the properties on the main type.
In my understanding the problem here is that the metadata contains properties which the the view model does not. However, this way I don't really understand the advantages of having a metadata class. So my questions are
1) Is there a way to prevent of throwing this exception?
2) If not, what it the best pattern to this situation? (like using a model, a viewmodel, which contains the subset of the properties of the model, defining data annotations by keeping the DRY approach).