views:

1626

answers:

6

Hi. I'm a newbie in the great world of NHibernate. I'm using version 2.0.1.GA. Here's my question. I have a table Cars with column Manufacturer(nvarchar(50)) and a primary key ID(int). My .NET class is:

public class Car
{
    public virtual int ID { get; set; }
    public virtual string Manufacturer { get; set; }
}

Now if I want to retrieve all cars made by Mercedes I have to type this:

using (var session = OpenSession())
{
    var cars = session
        .CreateCriteria(typeof(Car))
        .Add(Restrictions.Like("Manufacturer", "Mercedes"))
        .List();
    // ...
}

I don't like the fact that I need to specify the property name as a string :( Is it possible to have something more refactor friendly probably (it's only a suggestion)?

var ms = session
    .CreateCriteria<Car>()
    .Add(c => c.Manufacturer, Restrictions.Like("Mercedes")
    .List();

Anything like thins in the current version (2.0.1.GA) or in a future version?

+4  A: 

You could probably do this with NHibernate.Linq. It is in a usable form, but still a ways from being complete. Its currently living inside nhcontrib, the only way to get it is to pull it out of svn here https://nhcontrib.svn.sourceforge.net/svnroot/nhcontrib/trunk/src/NHibernate.Linq/

Matt Briggs
+6  A: 

Like Google Ninja said, you can do it with NHibernate.Linq. The query would then be:

session.Linq<Car>.Where(c => c.Manufacturer == "Mercedes").ToList()

I've used a binary that came bundled with fluent-nhibernate that works with 2.0GA (I think, not sure about the particular revision).

Bruno Lopes
Thanks, didn't have the syntax off the top of my head, +1
Matt Briggs
I might observe that "like" and "equals" will not produce the same results. I recently tried (not very hard) to find a way to do "like" in NHibnate.Linq. I gave up and used ICriteria instead.
Tim Scott
A: 

Thanks Bruno I will take a look at fluent-nhibenate. It's not exactly what I want but I think it still can be useful. Probably NHibernate.Linq is what I need but it seems to me the project is dead. It's no more developed and it didn't appear in the list of NHibernate Contrib projects. Am I right ?

Petar Petrov
AFAIK fluent-nhibernate is only for mapping, not for querying
Mauricio Scheffer
+1  A: 

Look at this question here. Someone had the same worry, and from I can gather, NHibernate.Linq is well alive.

Bruno Lopes
+6  A: 

If you don't want to use Linq to NHibernate yet, there's a couple of alternatives to get strongly type Criteria queries:

Mauricio Scheffer
+1  A: 

You can find what you are looking for here (blog entry) or here (google repository)

BjartN