sqldatareader 转实体类 最简单

public static object DataReaderToEntity(IDataReader dr, object entity)
{
    try
    {
        PropertyInfo[] pilist = entity.GetType().GetProperties();
        foreach (PropertyInfo pi in pilist)
        {
            for (int i = 0; i < dr.FieldCount; i++)
            {
                if (pi.Name.Equals(dr.GetName(i)))
                {
                    pi.SetValue(entity, Convert.ChangeType(dr[i], pi.PropertyType), null);
                }
            }
        }
        return entity;
    }
    catch
    {
        return null;
    }
}


用法:

Entity entity = (Entity)DataReaderToEntity(dr, new Entigy());

你可能感兴趣的:(reader)