I am trying to make helper classes to map my ViewModels to domain models and back + map validation errors from domain models to controller's ModelState (automatically create correct '.PropertyName' notation for nested view models). I am using ASP.NET MVC. I've created BaseViewModel that will provide means to specify concrete property mappings and will store them. When needed concrete ViewModels will map themselves to and from domain models + stored mappings will be used to map domain model errors.
public abstract class BaseViewModel
{
public void AddMap<TThisModel, TTargetModel, TProperty>(
Expression<Func<TThisModel, TProperty>> source,
Expression<Func<TTargetModel, TProperty>> target)
where TThisModel : BaseViewModel
{
// Store mappings for later usage.
}
}
public class ViewModel : BaseViewModel
{
public string Prop1 { get; set; }
public ViewModel()
{
AddMap<ViewModel, DomainModel, string>(x => x.Prop1, y => y.Prop2);
}
}
public class DomainModel
{
public string Prop2 { get; set; }
}
Is it possible to:
Get rid of TProperty generic when AddMap is invoked without losing ability to verify that both properties has same type at compile time? Can it be determined from AddMap arguments automatically?
Get rid of TThisModel generic since it will always be the same as the type of class, where it is invoked?
Constrain both expressions to be member access?
P.S. I do not want to use automatic mapping solutions, since they bring potential errors, which cannot be determined at compile time. I also would like to use expressions to specify mappings instead of direct assignment, because these mappings can be later used by another class to map domain model errors to ModelState.
P.P.S. May be better idea would be to move all mapping related logic to separate class and use composition + interfaces instead of inheritance. I've not decided yet.