johnllao

August 16, 2010

Using SQL string in Fluent NHibernate

Filed under: Uncategorized — johnllao @ 1:13 am

Sample code only shows how to execute a simple SQL string using Fluent NHibernate. Basically the method here will also work with Hibernate except that mapping will be on a .xml file.

First we have to create a the Entity and mapping class.

/// <summary>
/// 
/// </summary>
public class Planet
{
    private int _Id;
    /// <summary>
    /// 
    /// </summary>
    public virtual int Id
    {
        get { return _Id; }
        set { _Id = value; }
    }
    private string _Name;
    /// <summary>
    /// 
    /// </summary>
    public virtual string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
}

/// <summary>
/// 
/// </summary>
public class PlanetMap : ClassMap<Planet>
{
    /// <summary>
    /// 
    /// </summary>
    public PlanetMap()
    {
        Id(x => x.Id).Column("id");
        Map(x => x.Name).Column("name");
    }
}

Now lets go to the actual method.

/// <summary>
/// 
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
    ISessionFactory sessionFactory = Fluently
                .Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(GetConnectionString()))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
                .BuildSessionFactory();

    using (ISession session = sessionFactory.OpenSession())
    {
        // Executing sql string query
        ISQLQuery query = session.CreateSQLQuery("SELECT id, name FROM planet");

        // Getting result in a form of nested arrays
        Collection<Planet> planets = new Collection<Planet>();
        IList result = query.List();
        foreach(object[] item in result)
        {
            planets.Add(new Planet() { Id = (int) item[0], Name = (string) item[1] });
        }
    }

    Console.WriteLine("Press enter key to exit.");
    Console.ReadLine();
}

From the example above we used the ISQLQuery object to define and execute the query, please note that the result is in the form of a nested array of objects.

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.