This is for IQueryable data which is coming from Sql database.
Also I have created following code but I am stuck on just mapping of dynamic fields. Can you please check how can I map fields from dictionary to the object and then project to that object to new object.
I am able to project to the new object along with custom fields but I am not able to map values for custom fields which are in the collection of source object.
var baseType = typeof(CustomerGridViewModel);
var assembly = new AssemblyName("SedonaOneDynamicAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("SedonaOneTransientModule");
var typeBuilder = moduleBuilder.DefineType(
"CustomerGridPlusViewModel",
TypeAttributes.Public
| TypeAttributes.Class
| TypeAttributes.AutoClass
| TypeAttributes.AnsiClass,
baseType
);
var fields = DealerCustomFieldServiceDI.GetDealerCustomFieldsByEntityId(EntityEnum.Customer.ToInt32(), false);
var toMap = new Dictionary<string, string>();
foreach (var field in fields)
{
Type fieldType = typeof(string);
var propName = $"_CUSTOM_{field.Name}";
var fieldBuffer = typeBuilder.DefineField(propName, fieldType, FieldAttributes.Public);
toMap.Add(propName, field.Name);
}
var t = typeBuilder.CreateType();
var stuff = DealerCustomersServiceDI.GetCustomersForGrid(isMasterCustomer, isProspect, isInactive);
var mapperConfig = new MapperConfiguration(cfg =>
{
var customerType = typeof(aCustomer);
cfg.AddProfile<MappingProfile>();
var map = cfg.CreateMap(baseType, t);
;
foreach (var x in toMap)
{
map.ForMember(x.Key, opt => opt.MapFrom("CustomFieldValues")); // this is the part I need to solve
}
// this "CustomFieldValues" is collection in source object(basetype) which contains following structure:
/*
//public class CustomFieldValue
// {
// public string Name { get; set; }
// public string Value { get; set; }
//
// }
I need to map field name as present in dictionary with the value of same field present in this collection
*/
});
var mapper = mapperConfig.CreateMapper();
var methodInfo = mapper.GetType()
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)
.Where(x => x.Name.EndsWith("ProjectTo"))
.FirstOrDefault();
var genericMethodInfo = methodInfo.MakeGenericMethod(t);
var eType = typeof(Expression<>);
var fType = typeof(Func<,>);
var fgType = fType.MakeGenericType(t, typeof(object));
var egType = eType.MakeGenericType(fgType);
var eArray = Array.CreateInstance(egType, 0);
var result = genericMethodInfo.Invoke(mapper, new object[] { stuff, null, eArray }) as IQueryable<dynamic>;
result variable contains a query and when I do result.ToList() then it maps all the properties but not the custom field which are coming always Null because I have not mapped their values to come from.