戰地連結︰ Home My Flickr NBA.com About

2008年8月5日星期二

Convert NHibernate result iList to DataSet

Overview

Just like Hibernate, NHibernate returns query result in List of Objects (that's the idea of O/R mapping). It is very good, but some ASP.NET tools only work with DataSet, so we have to explicitly convert the iList returned by NHibernate to DataSet. The following simple code snippet mainly copied from Ayende's Blog can server this purpose.

Reference

Converting an object collection to a DataSet

Code Snippet

public static IList<Company> ShowCompanies()

        {

            // Get the List of Companies

            ICriteria criteria = NHibernateHttpModule.CurrentSession.CreateCriteria(typeof(Company));

            IList<Company> companies = criteria.List<Company>();

 

            // Convert the List into DataSet & return it

            DataTable dt = new DataTable();

            dt.Columns.Add("Name", typeof(string));

            dt.Columns.Add("CompanyCode", typeof(string));

            foreach (Company comp in companies)

            {

                DataRow row = dt.NewRow();

                row["Name"] = comp.Name;

                row["CompanyCode"] = comp.CompanyCode;

                dt.Rows.Add(row);

            }

            DataSet ds = new DataSet();

            ds.Tables.Add(dt);

            return ds;

            return companies;

        }

沒有留言: