for CsvHelper i have used Map function for simple use for object
MemberInfo dMember = new Contact().GetType().GetProperty("FirstName"));
Map(typeof(Contact), dMember).Name("fname"); //works simple conversion
Here FirstName and fname both comes from configuration which is in Json file \
Now next object which is a List of another class i cannot do.Name i need use .ConvertUsing and do some merging of fields from CSV file i will have 3 fields Email1,Email2,Email3 which has to map to List where Email is a class and has property of an email address.
I was successful to find a way to use dynamic lambda function because Map(x=>x.Email) has to be custom and it should be able to do conversion for any object
string field = "EmailAddresses"; //field name of a class
string exp = $"c.{field}";
var p = Expression.Parameter(typeof(Contact), "c");
var e = DynamicExpressionParser.ParseLambda(new[] { p }, null, exp);
// now here e.ReturnType is List<Email> but i cannot use List<Email> instead of dynamic because this
//function will also be called for other types so it has resolve at runtime. This maping fails with cannot convert Type Email to Type Object
Map((Expression<Func<Contact, List<dynamic>>>)e).ConvertUsing(row =>
{
dynamic list = new List<ExpandoObject>();
dynamic email = new ExpandoObject();
var emailAddress = row.GetField("email_address");
email.EmailAddress = (emailAddress != null) ? emailAddress:"abc@g.com";
list.Add(email);
return list;
}
Aucun commentaire:
Enregistrer un commentaire