I have two C # classes that have many of the same properties (by name and type). I want to be able to copy all non-zero values from a Defect instance to a DefectViewModel instance. I was hoping to do this with reflection using GetType().GetProperties() . I tried the following:
var defect = new Defect(); var defectViewModel = new DefectViewModel(); PropertyInfo[] defectProperties = defect.GetType().GetProperties(); IEnumerable<string> viewModelPropertyNames = defectViewModel.GetType().GetProperties().Select(property => property.Name); IEnumerable<PropertyInfo> propertiesToCopy = defectProperties.Where(defectProperty => viewModelPropertyNames.Contains(defectProperty.Name) ); foreach (PropertyInfo defectProperty in propertiesToCopy) { var defectValue = defectProperty.GetValue(defect, null) as string; if (null == defectValue) { continue; }
What would be the best way to do this? Do I have to maintain separate Defect and DefectViewModel property lists so that I can do viewModelProperty.SetValue(viewModel, defectValue, null) ?
Edit: Thanks to the answers of Jordão and Dave , I chose AutoMapper. DefectViewModel is in a WPF application, so I added the following App constructor:
public App() { Mapper.CreateMap<Defect, DefectViewModel>() .ForMember("PropertyOnlyInViewModel", options => options.Ignore()) .ForMember("AnotherPropertyOnlyInViewModel", options => options.Ignore()) .ForAllMembers(memberConfigExpr => memberConfigExpr.Condition(resContext => resContext.SourceType.Equals(typeof(string)) && !resContext.IsSourceValueNull ) ); }
Then, instead of all this PropertyInfo business, I only have the following line:
var defect = new Defect(); var defectViewModel = new DefectViewModel(); Mapper.Map<Defect, DefectViewModel>(defect, defectViewModel);
reflection c # properties mapping
Sarah Vessels Aug 31 '10 at 16:03 2010-08-31 16:03
source share