views:

45

answers:

1

Why is no SQL being generated when I run my Nhibernate 3 query?

    public IQueryable<Chapter> FindAllChapters()
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            var chapters = session.QueryOver<Chapter>().List();

            return chapters.AsQueryable();
        }
    }

If I run the query below I can see that the SQL that gets created.

    public IQueryable<Chapter> FindAllChapters()
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            var resultDTOs = session.CreateSQLQuery("SELECT Title FROM Chapter")
                    .AddScalar("Title", NHibernateUtil.String)
                    .List();

            // Convert resultDTOs into IQueryable<Chapter>
        }
    }
+2  A: 

Linq to NHibernate (like Linq to entities) uses delayed execution. You are returning IQueryable<Chapter> which means that you might add further filtering before using the data, so no query is executed.

If you called .ToList() or .List() (i forget which is in the API), then it would actually produce data and execute the query.

In other words, right now you have an unexecuted query.

Added: Also use Query() not QueryOver(). QueryOver is like detached criteria.

For more info, google "delayed execution linq" for articles like this

Tim Hoolihan
I am calling .List() on this line "var chapters = session.QueryOver<Chapter>().List();" I checked to see if .ToList() was an option but it isn't. It must be some something else.
Tarzan
switch to .Query<Chapter> not QueryOver. QueryOver is like detached critera
Tim Hoolihan
.ToList() should be an option. If not, you need to import the System.Linq namespace.
codekaizen
Try your example with Query and import System.Linq so you can use .ToList(), that should do it. The real key is you need to make sure you're returning actual data, not an expression tree.
Tim Hoolihan
Thank you for the suggestions. I was using NHibernate3 Beta and it has .QueryOver<> rather than .Query<> and has .List() and not .ToList(). I decided to use NHibernate2 to resolve my problems. NHibernate2 and it has .Query<> and .ToList().
Tarzan
I'm using NHibernate 3 beta as well, and those methods are available. You have to have "using NHibernate.Linq;" and make sure you are referencing Remotion.Data.Linq (comes with NH3 zip)
Tim Hoolihan