对于外部系统的常规过滤,我需要按目标路径获取映射的源路径。
CreateMap<Record, Contact>()
.ForMember(x => x.Id, opt => opt.MapFrom(c => c.Id))
.ForMember(x => x.PersonInformation, opt => opt.MapFrom(c=>
new PersonInformation()
{
FirstName = c.FirstName,
LastName = c.LastName,
MiddleName = c.MiddleName,
ExternalReferences = new List<ExternalReference>() { new ExternalReference { Id = 1, Ref = c.Id } }
}
))
我创建了函数,但是它仅适用于简单的路径,例如: Contact.Id => Record.Id 但是它不起作用 Contact.PersonInformation.FirstName =将映射到> Record.FirstName
public (PropertyInfo propertyInfo, string path) GetDestinationPropertyFor(string sourcePropertyPath, Type salesforceType, Type swaggerType)
{
var properties = sourcePropertyPath.Split('.');
var destinationProperties = new List<string>();
PropertyInfo propertyInfo = null;
foreach (var property in properties)
{
var map = _mapper.FindTypeMapFor(salesforceType, swaggerType);
var propertyMap = map.PropertyMaps.First(pm => pm.DestinationMember == swaggerType.GetProperty(property));
propertyInfo = propertyMap.SourceMember as PropertyInfo;
var jsonProperty = propertyInfo.GetCustomAttribute(typeof(JsonPropertyAttribute));
destinationProperties.Add(((JsonPropertyAttribute)jsonProperty).PropertyName);
swaggerType = propertyMap.Types.DestinationType;
salesforceType = propertyMap.Types.SourceType;
}
var destinationPropertyPath = string.Join('.', destinationProperties);
return (propertyInfo, destinationPropertyPath);
}