问题描述:

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.

网友答案:

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.

相关阅读:
Top