views:

28

answers:

2

Hi,

Im pretty new to nhibernate so this may be quite straightforward but i havent found an answer on the web yet.

Lets say i have a Parent class and a Child class. The Parent Class can have many Child classes associated with it. Now when i try to load a specific Parent nhibernate also populates its Child collection for me. There are situations where I want to just return a Parent class without a Child collection.

I know i can turn on Lazy loading but that wont work as im serializing the Parent to XML. The XML serialiser cannot work with the nhibernate PersistanceBag that contains the Child collection.

So is there a way to define a Parent class, lets say ParentView which works on the same table but only contains the Parent properties and not all its children and grandchildren?

+3  A: 

Define a class ParentView that contains the columns you need to retrieve. Make sure this class has one parameterless constructor.

ISession session = NHibernateHelper.Session;
ISQLQuery query = session.CreateSQLQuery("select Parent_ID, Name form Parent where Parent_ID = :parentID");
query.SetInt32("parentID", parentID);
IList<ParentView> parentView = query.SetResultTransformer(Transformers.AliasToBean<ParentView>()).List<ParentView>();
return parentView;
sh_kamalh
Looks interesting, Im using fluentnhibernate and im pretty new to nhibernate in general. Is there a way to achieve the same result using fluent?
Kaius
Fluent NHibernate is the mapping helper. This solution presented above is a query and doesn't fall within the scope of Fluent NHibernate.
Michael Gattuso
Yup this worked a treat. Thanks.
Kaius
A: 

An alternative to creating a view class and associated query as suggested by sh_kamalh (which I would consider if I were you). If the problem is related to the bag mapping structure specifically then you might have a couple of easier solutions:

Option 1

Revisit the bag mapping - Maybe simple selecting a different strategy will fix the issue. I have answered a question on the different collection mappings before http://stackoverflow.com/questions/1916350/set-bag-and-list-set-in-nhibernate/1921727#1921727 personally I find that I use the Set strategy a lot. To map a different strategy in Fluent NHibernate use the following as a guide in your override.

mapping.HasMany<Child>(x => x.Children).ToSet();

or

mapping.HasMany<Child>(x => x.Children).ToList();

Option 2

Not particularly related to NHibernate but if you are using the default xml serializer you might be able to tell the xml serializer to simply ignore that property and leave the bag mapping in place.

[System.Xml.Serialization.XmlIgnore]
public IEnumerable<Child> Children { get; internal set; }
Michael Gattuso