无法在lambda表达式(CsvHelper)中强制转换类型错误的对象

问题描述 投票:0回答:1

使用CsvHelper和ClassMap将对象模型映射到输出。尝试通过lambda表达式动态生成映射。到目前为止:

public class BaseClassMap<TClass> : ClassMap<TClass> where TClass : class
{
    public BaseClassMap(List<string> columns)
    {
        var index = 0;
        PropertyInfo[] props = typeof(TClass).GetProperties();
        foreach (PropertyInfo prop in props)
        {
            index = columns.IndexOf(prop.Name);
            if (index != -1)
            {
                var columnAttribute = prop.GetCustomAttributes(false).FirstOrDefault(a => a.GetType() == typeof(ColumnAttribute)) as ColumnAttribute;

                var parameterExpression = Expression.Parameter(typeof(TClass), "x");
                var memberExpression = Expression.PropertyOrField(parameterExpression, prop.Name);
                var memberExpressionConversion = Expression.Convert(memberExpression, typeof(object));
                var lambda = Expression.Lambda<Func<TClass, object>>(memberExpressionConversion, parameterExpression);
                Map<object>(lambda).Index(index).Name(columnAttribute != null ? columnAttribute.Name : prop.Name);
            }
        }
    }
}

正在获取:

无法将类型为CsvHelper.Configuration.MemberMap 2[KXL_CDMS_svc.Data.Entities.ExpTempApplication.TempEnvPermitTrackingCdms,System.String]的对象转换为类型为CsvHelper.Configuration.MemberMap 2[KXL_CDMS_svc.Data.Entities.ExpTempApplication.TempEnvPermitTrackingCdms,System.Object]

at

Map<object>(lambda).Index(index).Name(GetTitle(columnAttribute != null ? columnAttribute.Name : prop.Name));

lambda表达式的新特性。有什么建议吗?

c# linq-expressions csvhelper
1个回答
0
投票

您只需要使用Map方法的其他重载。

public class BaseClassMap<TClass> : ClassMap<TClass> where TClass : class
{
    public BaseClassMap(List<string> columns)
    {
        var index = 0;
        PropertyInfo[] props = typeof(TClass).GetProperties();
        foreach (PropertyInfo prop in props)
        {
            index = columns.IndexOf(prop.Name);
            if (index != -1)
            {
                var columnAttribute = prop.GetCustomAttributes(false).FirstOrDefault(a => a.GetType() == typeof(ColumnAttribute)) as ColumnAttribute;

                Map(typeof(TClass), prop).Name(columnAttribute != null ? columnAttribute.Name : prop.Name);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.