views:

86

answers:

2

I'm still new with NHibernate, so correct me if I'm wrong on any of this.

When you are using NHibernate to build collections of objects from database records, NH takes care of instantiating your collections and populating them.

How do you instantiate your ISet collections when you are writing tests that don't actually use NH?

A: 

Assuming you're testing something other than the data layer itself (like your domain logic, for example), you can simply create the objects yourself and populate them with test case data. Or you could be really sneaky and create a database with all your test cases.

Jon Seigel
+1  A: 

You can instantiate a field by using the constructor or by instantiating the field directly in the declaration. Classes mapped with NHibernate can be persistence ignorant.

public class MyEntity
{
   private readonly ISet<ChildEntity> children;

   public MyEntity()
   {
      children = new HashedSet<ChildEntity>();
   }

   public IEnumerable<ChildEntity> Children
   {
      get { return children; }
   }

   public void AddChild(Child child)
   {
     children.Add(child);
   }
}
Paco
You can initialize your collection in field as well: private readonly ISet<ChildEntity> children = new HasedSet<ChiledEntity>(); That way you don't have to write constructor.
Marek Tihkan
Why do your property and field types differ?
Ronnie Overby
@Ronnie Overby: What do you mean? The mapping?@Marek Tihkan: That's true (see edit)
Paco
No, in the class, your children field is of type ISet<ChildEntity> but the property that exposes it is of type IEnumerable<ChildEntity>. Why not make them the same?
Ronnie Overby
Because I want to make my aggregate root (in ddd terms, MyEntity ) responsible for it's children. I want to expose the collection as readonly to the world outside of my aggregate root. Google for aggregate root to read more about this concept. When you prefer it, you can expose the ISet to the outer world. Just change IEnumerable<ChildEntity> to ISet<ChildEntity> in the code above. The ddd aggregate root concept has nothing to do with NHibernate, it's just abut modelling your domain to your code. You can say "add a child to the parent" or you can say "add a child to the children of the parent"
Paco