2

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.

1

2 Answers 2

1

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>();
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.