自动映射IDataReader到列表<t> - 缺少类型映射配置或不支持的映射

时间:2016-06-15 13:40:54

标签: c# mapping automapper datareader idatareader

正如标题所示我试图将DataReader对象映射到对象列表,这里是我正在使用的代码,我使用AutoMapper 4.2.1和3.3.1尝试了这个

Mapper.Initialize(cfg =>
            {
                 cfg.CreateMap<IDataReader, MemberChangesDto>()                
                .ForMember(dest => dest.MemberNo, opt => opt.MapFrom(src => (string)src["Member_No"]))
                .ForMember(dest => dest.OrganisationName, opt => opt.MapFrom(src => (string)src["Member_Name"]))
                .ForMember(dest => dest.MemberJoinDate, opt => opt.MapFrom(src => (string)src["Membership_StartDate"]))
                .ForMember(dest => dest.ResignationDate, opt => opt.MapFrom(src => (string)src["Membership_Resigned_Date"]))
                .ForMember(dest => dest.MemberStatusId, opt => opt.MapFrom(src => (string)src["Membership_Status_Code"]));
            }
            );

初始化自动化程序后,我使用

进行验证
Mapper.AssertConfigurationIsValid();

这不会返回错误,然后我调用映射

IDataReader dataTableReader = memberChangesDS.Tables[2].CreateDataReader();
IList<MemberChangesDto> members = Mapper.Map<IList<MemberChangesDto>>(dataTableReader);

然而,这会返回错误

  

{&#34;缺少类型映射配置或不支持的映射。   映射类型:   IDataReader - &gt; IList 1 System.Data.IDataReader -> System.Collections.Generic.IList 1 [[MemberChangesDto,Models,   版本= 1.0.0.0,文化=中立,   公钥=空]]   目的地路径:   IList`1   来源值:System.Data.DataTableReader&#34;}

我想要映射的对象看起来像这样。

public class MemberChangesDto
{
    public string MemberNo { get; set; }
    public string OrganisationName { get; set; }
    public string MemberJoinDate { get; set; }
    public string ResignationDate { get; set; }
    public string MemberStatusId { get; set; }
}

任何人都可以指出我正确的方向,我已经使用AutoMapper从对象到对象毫无问题,但我认为IDataReader在这里引起了问题。

提前致谢。

1 个答案:

答案 0 :(得分:1)

此方法使用不使用AutoMapper的SQL查询创建对象实例:

   public IEnumerable<T> FillDataRows<T>(String query, params SqlParameter[] sqlParams) {
        var properties = typeof(T).GetProperties().ToList();
        IList<T> result = new List<T>();

        var source = FillDataRows(query, sqlParams).ToList();
        var firstInSource = source.FirstOrDefault();
        if (firstInSource == null)
            return result;

        //remove properties not exist in source
        properties.RemoveAll(p => firstInSource.Table.Columns.Contains(p.Name) == false);

        foreach (var row in source) {
            var item = createItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }

    private T createItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) {
        T item = Activator.CreateInstance<T>();
        foreach (var property in properties) {
            if (row[property.Name] != System.DBNull.Value)
                property.SetValue(item, row[property.Name], null);
        }
        return item;
    } 

    public void FillDataSet(DataSet ds, String dataTable, String query, params SqlParameter[] sqlParams) {
        using (var cn = new SqlConnection(this.connectionString)) {
            cn.Open();
            using (var cmd = cn.CreateCommand()) {
                cmd.CommandTimeout = commandTimeout;
                cmd.CommandText = query;
                if (sqlParams != null && sqlParams.Length > 0)
                    cmd.Parameters.AddRange(sqlParams);
                using (var adapter = new System.Data.SqlClient.SqlDataAdapter(cmd)) {
                    adapter.Fill(ds, dataTable);
                }
            }
            cn.Close();
        }
    }

    public IEnumerable<DataRow> FillDataRows(String query, params SqlParameter[] sqlParams) {
        var ds = new DataSet();
        FillDataSet(ds, "Result", query, sqlParams);
        return ds.Tables["Result"].Rows.OfType<DataRow>();
    }

样品:

var sql = "select MemberNo = Member_No, OrganisationName = Member_Name ... From MYTABLES where Member_No = @ID"; 
var results = FillDataRows<MemberChangesDto>(sql, new SqlParameter("@ID", 12345));