Add list item by ID

62 Views Asked by At

Let's say:

public class Parent
{
    public virtual IList<Child> Childs { get; set; }

    public void AddChild(long childId)
    {
        // Link existing child to parent.
    }
}

I'm trying to implement DDD using NHibernate so I wonder how to link child item to parent without retrieving it from database.

1

There are 1 best solutions below

0
Jamie Ide On

You can't. The object oriented approach would be:

public class Parent
{
    public virtual IList<Child> Childs { get; set; }

    public void AddChild(Child child)
    {
        child.Parent = this;
        Childs.Add(child);
    }
}

The code that calls this method could add a child without retrieving it using ISession.Load:

var child = session.Load<Child>(childId);
parent.AddChild(child);

Load will create a dynamic proxy with the ID set. Note that child will be loaded if you access any of its other properties, and that accessing the parent's Childs collection will cause it to be loaded.