开发者

How can one fetch partial objects in NHibernate?

I have an object O with 2 fields - A and B. How can I fetch O from the database so that only the field A is fetched?

Of course, my real application has objects with many more fields, but two fields are enough to understand the principal.

I am using NHibernate 2.1.

Thanks.

EDIT:

I wish to clarify. I need to fetch objects of type O. Sometimes I will want to fetch complete objects - meaning both A and B fields are set from the database values. But on other occasions, I would like to fetch开发者_如何转开发 O objects with just the A field set from the database values.


Use a projection to narrow the result set to the desired column(s) and a result transformer to convert the result into the type that you want.

This will return transient objects rather than persistent entities.

// select some User objects with only the Username property set
var u = session.CreateCriteria<User>()
    .SetProjection( Projections.ProjectionList().Add(Projections.Property("Username"), "Username")  ) 
    .SetResultTransformer( Transformers.AliasToBean<User>() )
    .List<User>();


HQL has a select new construct, which allows you to fetch only a subset of fields. Objects returned, however, cannot be saved back to the DB.

As an alternative, you can create additional classes with a limited set of properties an map those onto table in question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜