简体   繁体   中英

Add list item by ID

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM