Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lambda expressions and NHibernate

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?

like image 314
Petar Petrov Avatar asked Dec 04 '08 16:12

Petar Petrov


2 Answers

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()

If someone ends up here and is using NH3.0 the syntax is just a tad different (thanks to Michael Mrozek and Mike for the suggestion):

session.Query<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).

like image 73
Bruno Lopes Avatar answered Oct 02 '22 11:10

Bruno Lopes


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

  • http://bugsquash.blogspot.com/2008/03/strongly-typed-nhibernate-criteria-with.html
  • http://www.kowitz.net/archive/2008/08/17/what-would-nhibernate-icriteria-look-like-in-.net-3.5.aspx
like image 45
Mauricio Scheffer Avatar answered Oct 02 '22 12:10

Mauricio Scheffer