开发者

NHibernate: Lazyload single property

开发者 https://www.devze.com 2022-12-13 20:05 出处:网络
I have currently moved my blogengine over from Linq2Sql to NHIbernate. I\'m stuck at the following performance problem:

I have currently moved my blogengine over from Linq2Sql to NHIbernate.

I'm stuck at the following performance problem: I got one table: 'Posts', that has Id, Title, PostContent, DateCreated collumns and so on.

The problem is that, when I'm creating the "Recent posts list", I don't want the whole PostContent.

In Linq2Sql you can set lazy loading on a single property, so it won't be part of the SQL query until you actually ask for the property.

I tried doing this with Fluent NHibernate, by doing this:

Map(x => x.PostContent).LazyLoad();

It didn't work out. Googling around, it seems that NHibernate doesn't support this, so my question is, how can I fix this?

Is it really not possible to lazy load my property without moving the content to a seperate table?

Thanks in ad开发者_Go百科vance!


Update: this capability is now available in the NHibernate trunk.

See details on Ayende's blog, where the sample is exactly the scenario you describe here.


Here is how you can achieve what you want (kind of lazy loading but not the same)

var posts = NHibernateSessionManager.Session.CreateQuery("Select p.Id as Id, p.Title as Title, p.DateCreated as DateCreated from Post p")
                .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(Post)))
                .List<Post>();

What the AliasToBean is intended for is, doing selects for specific columns (usually from more than one entities) and return a strongly typed collection instead of a System.Object[].

Now if you Bean (class) is your Post class then it will popultate to that class ONLY the requested columns and nothing else.

What you will NOT be having though is a collection of NHibernate managed objects. All Posts in the returned lists are detached non controlled objects.

For doing things like "getting all recent posts" without having to get the most "heavyweight" columns of your entity while not having to create other classes to convert the data to, the above solution is kind of perfect.

Check this out for more info: NHibernate: returning a strongly typed list having applied an aggregate function


This is not possible when PostContent is mapped to the same table, because the performance difference is not significant in 99% of the situations. When you are in the 1%, you can consider using handbuild sql instead of a orm for that case.

Lazy/Eager loading is not possible at all with linq to sql (out of the box) as far as I know.

What you can do create a different class with the data you want to select and just select that data into a new object.

0

精彩评论

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