Rishabh Ohri
Rishabh Ohri

Reputation: 1310

Querying selected columns with NHIbernate?

In my POCO class I have 16 attributes that are mapped to the database table with 16 columns. Now I have to write methods that only fetch a subset of columns from the table using NHIbernate. How to perform this thing when I dont want to fetch all the attributes of the persisted objects in the database.

Upvotes: 2

Views: 456

Answers (2)

Lachlan Roche
Lachlan Roche

Reputation: 25946

Projections enable the returning of something other than a list of entities from a query.

var proj = Projections.ProjectionList()
    .Add(Projections.Property("Id"), "Id")
    .Add(Projections.Property("Username"), "Username");

var list2 = DetachedCriteria.For<User>()
    .Add(Expression.Eq("Username", "lachlan"))
    .GetExecutableCriteria( sessionFactory.GetCurrentSession())
    .SetProjection( proj )
    .List();

NHibernate can also map the projected result to a typed list.

var proj = Projections.ProjectionList()
    .Add(Projections.Property("Id"), "First")
    .Add(Projections.Property("Username"), "Second");

var list2 = DetachedCriteria.For<User>()
    .Add(Expression.Eq("Username", "lachlan"))
    .GetExecutableCriteria( sessionFactory.GetCurrentSession())
    .SetProjection( proj )
    .SetResultTransformer(Transformers.AliasToBean(typeof(Pair)))
    .List<Pair>();

Upvotes: 1

Joel
Joel

Reputation: 19358

The current release does not support lazy loading parts of a class (I believe the upcoming release does include this feature).

For the present you can follow the workaround proposed here.

Upvotes: 0

Related Questions