tags:

views:

455

answers:

3

Let's say that I have classes like this:

public class Parent
{
   public int ParentId {get;set;}
   public IList<Child> Children {get;set;}
   public string Name {get;set;}
}

public class Child
{
   public int ChildId {get;set;}
}

Someone calls a method to save a new Parent and passes me a name and a list of Child IDs, and I want to save the Parent. Is there a way that I can save the Parent and associate the Child IDs to it without loading up the Child objects and then adding them to the Children collection? It seems like a waste to load up objects just so that I can get NHibernate to save them when I already have the IDs, which would be all I would need to save the Parent if I did it in a stored procedure.

using... NHibernate 2.0.1GA, SQL Server 2005

Jon

A: 

If the Parent is associated with the Children then there should be a Parent property in every Child (which I don't see) and you'll have to update the Children anyway, so you'll have to load all the children from the database.

Otherwise, how is the relationship between the parent and the children persisted? If it's not just save the parent with the Name property and don't even bother with the children.

gcores
A: 

You can either map a collection of integers (i.e. Parent.Children as an IList<int>), or you can map a collection of objects (i.e. Parent.Children as an IList<Child>). If you map the objects then you must update the DB using objects, i.e. you will need to load the Child objects in order to save the Parent. If you choose to map the integers IDs instead, then you can update via IDs.

PS. If your IDs are some other primitive type (e.g. guids, strings, etc), then the same argument still applies.

John Rayner
+1  A: 

Something like this will work i think

var child1 = Session.Load<Child>(12);
var child2 =Session.Load<Child>(23);
var parent = Session.Get(253);
parent.Name = "new parent name";
parent.Children.Add(child1);
parent.Children.Add(child2);

When load is called it doesn't go to the database to get the data until it is actually access, so i would imagine this would also do the trick for you.

Gareth