0

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?

SecretDeveloper
  • 3,140
  • 2
  • 31
  • 36

2 Answers2

3

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
  • 3,853
  • 4
  • 38
  • 50
  • Looks interesting, Im using fluentnhibernate and im pretty new to nhibernate in general. Is there a way to achieve the same result using fluent? – SecretDeveloper Oct 15 '10 at 18:24
  • 1
    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 Oct 15 '10 at 18:57
0

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 List vs Set vs Bag in NHibernate 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; }
Community
  • 1
  • 1
Michael Gattuso
  • 13,020
  • 2
  • 25
  • 29