lundi 18 octobre 2021

How to dynamically map based on the field name using Auto mapper and Reflection

I have around 50 types having the same problem. The source has a (fieldName)specified field and depending on the value of the (fieldName)specified, I want to set the value for the field. So basically, if source (fieldName)Specified == true, then I want to set source fieldName value to destination fieldName. FieldName is dynamic; intSpecified, decimalTestSpecified, etc.

Example

if(decimalFieldSpecified == false){
  (source)decimalField? = null
}else{
 (source)decimalField? = decimalField
} 

What I have tried

   public static void GenericMappingWithNames(this Profile profile,
            Assembly assemblyFrom,
            Assembly assemblyTo,
            Func<Type, bool> typeFilter,
            string[] trimmedSuffixes = null)
        {
            var filteredFromTypes = assemblyFrom.GetTypes().Where(typeFilter).AsEnumerable();
            var typesTo = assemblyTo.GetTypes();

            foreach (var typeFrom in filteredFromTypes)
            {
                //Find types in assembly B with the same name. 
                var filteredTypesTo = typesTo.Where(x => TrimEnd(x.Name, trimmedSuffixes).Equals(TrimEnd(typeFrom.Name, trimmedSuffixes), StringComparison.InvariantCultureIgnoreCase));
                
                filteredTypesTo.ToList().ForEach(x =>
                {
                    //profile.CreateMap(typeFrom, x).ReverseMap();  

                    profile.CreateMap(typeFrom, x).ReverseMap().ForAllMembers(o =>
                    { 
                        var allSpecifiedMembers = o.GetType().GetProperties().Where(p=>p.Name.EndsWith("Specified")).ToList();

                        allSpecifiedMembers.ForEach((specified) =>
                        {
                            var propertyName = specified.Name.Replace("Specified", "");
                             
                            //hmm how do I get the (fieldName)specified value and check

                        }); 
                    }); 
                });
            }
        }

Type Examples

  public class Test
        { 
            public decimal test1 { get; set; }  
            public decimal test2 { get; set; }  
        }

        public class TestAgainst
        {
            public decimal test1 { get; set; }
            public bool test1Specified { get; set; }

            public decimal test2 { get; set; }
            public bool test2Specified { get; set; }

        }





Aucun commentaire:

Enregistrer un commentaire