/// <summary> /// Creates the source code for a mapping class. /// </summary> /// <param name="source"></param> /// <param name="target"></param> /// <returns></returns> private string GenerateMapClassCode(IMappingConfiguration configuration, out List <string> referenceList, out string fullName) { referenceList = new List <string>(); string sourceAssemblyFile = configuration.SourceType.Assembly.Location; string targetAssemblyFile = configuration.DestinationType.Assembly.Location; referenceList.Add(sourceAssemblyFile); referenceList.Add(targetAssemblyFile); string sourceTypeName = configuration.SourceType.Name; string sourceCast = configuration.SourceType.Name + " sourceObject = (" + configuration.SourceType.Name + ")source;\r\n"; string destinationCast = configuration.DestinationType.Name + " targetObject = (" + configuration.DestinationType.Name + ")destination;\r\n"; string targetCreate = configuration.DestinationType.Name + " targetObject = new " + configuration.DestinationType.Name + "();\r\n"; int classIndex = Interlocked.Increment(ref classCounter); fullName = string.Format("DynamicCode{0}.DynamicCodeMap{0}", classIndex); string mappingLines = string.Empty; string copyMappingLines = string.Empty; foreach (KeyValuePair <string, MemberMap> pair in configuration.Mappings) { MemberMap memberMap = pair.Value; if (memberMap == null) { continue; } if (!memberMap.Ignore) { mappingLines += memberMap.GenerateCode("sourceObject", "targetObject") + "\r\n"; } if (!memberMap.IgnoreOnCopy) { copyMappingLines += memberMap.GenerateCode("sourceObject", "targetObject") + "\r\n"; } // string.Format(FIELD_MAP, memberMap.MemberName, memberMap.SourceMemberName); } List <string> usingList = new List <string>(); usingList.Add(configuration.DestinationType.Namespace); usingList.Add(configuration.SourceType.Namespace); string usingCode = GenerateUsingCode(usingList); string code = @"namespace DynamicCode" + classIndex + @" { " + usingCode + @" public class DynamicCodeMap" + classIndex + @" : IMap { public object Map(object source) { if (source == null) return null; " + sourceCast + @" " + targetCreate + @" " + mappingLines + @" return targetObject; } public object Map(object source, object destination) { if (source == null || destination == null) return null; " + sourceCast + @" " + destinationCast + @" " + copyMappingLines + @" return targetObject; } } }"; return(code); }