R – NHibernate – Saving parent when I have children IDs only

nhibernate

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

Best Answer

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.

Related Topic