In my POCO class I have 16 attributes that are mapped to the database table with 16 columns. Now I have to write methods tha开发者_如何学JAVAt 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.
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>();
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.
精彩评论