The official Fatica Labs Blog! RSS 2.0
# Wednesday, 28 September 2011

This is just an example helper class to create a generic IResultTransformer that allow us to convert an NHibernate result into a string[] suitable for generating a CSV. Nothing advanced, just some basic stuff and a fluent interface syntax. Let’see the class:

class CsvTransformer<T>:IResultTransformer
    {
        List<Func<T, string>> mappers = new List<Func<T,string>>();
        Func<object,T> elemSelector = k=>(T)((object[])k)[0];
        public CsvTransformer()
        {
            
        }
        #region IResultTransformer Members

        public System.Collections.IList TransformList(System.Collections.IList collection)
        {
            List<string[]> csv = new List<string[]>();
            foreach (object elem in collection)
            {
                List<string> row = new List<string>();
                foreach (var map in mappers)
                    row.Add(map(elemSelector(elem)));
                csv.Add(row.ToArray());
            }
            return csv;
        }

        public object TransformTuple(object[] tuple, string[] aliases)
        {
            return tuple;
        }

        #endregion
        public CsvTransformer<T> Extract(Func<object, T> elemSelector)
        {
            this.elemSelector = elemSelector;
            return this;
        }
        public CsvTransformer<T> Map(Func<T, string> map)
        {
            mappers.Add(map);
            return this;
        }
    }

 

And an example usage can be:

session.QueryOver<MyEntity>()
                        .TransformUsing(newTransformers.CsvTransformer<MyEntity>()
                        .Map(k=>k.Field1)
                        .Map(k=>k.Field2)
                        .Map(k=>k.Date.HasValue?k.Date.Value.ToShortDateString():"")
                        )
                    .List<string[]>();

We can also customize how to extract data from the NHibernate returned tuple by using the .Extract method.

Easy to use and to embed as a stand alone file in our projects. What about having something similar integrating AutoMapper ?

Wednesday, 28 September 2011 15:47:56 (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
NHibernate

My Stack Overflow
Contacts

Send mail to the author(s) E-mail

Tags
profile for Felice Pollano at Stack Overflow, Q&A for professional and enthusiast programmers
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2019
Felice Pollano
Sign In
Statistics
Total Posts: 157
This Year: 0
This Month: 0
This Week: 0
Comments: 127
This blog visits
All Content © 2019, Felice Pollano
DasBlog theme 'Business' created by Christoph De Baene (delarou) and modified by Felice Pollano