0

I have an object model similar to this:

    public class Item
    {
        public virtual Guid Id { get; set; }
    }

    public class Box
    {
        public virtual Guid Id { get; set; }
        public virtual IList<Item> Contents { get; protected set; }

        public Box()
        {
            Contents = new List<Item>();
        }
    }

What I want to do is be able to get an Item's parent (being the box it is in). Normally I would create a field on the Item called Parent and handle the one-to-many relationship in a manual mapping, but we are trying to use automapping on this project. Is there someway I can create either a Box or a BoxId field ID on the Item and have FNH auto-maigially populate for me when object (in this case Box) is saved?

Thanks!

James Bender
  • 1,175
  • 1
  • 11
  • 22
  • setting the parent when the item is added to Contents collection will and should not be done by FNH because transient instances would be broken. However it is possible to have a convention which associates the Parent Property with the collection. Is that what you want? – Firo Jan 16 '15 at 07:52
  • I want to do something like var box = item.Parent. Before Automapping I would have an AddItem method on Box and a Parent field on Item. Before the Item was added to the list I would do something like item.Parent = this but I noticed that with Automapping FNH was creating a FK field on the Item table for me anyway. I'm just trying to avoid duplication of data/work. It seems to me like this would be a pretty standard piece of functionality (the relationship I mean) and would be supported. If it isn't then it isn't, but I want to find out before I start slingin' code. – James Bender Jan 16 '15 at 14:24

1 Answers1

1

in the object model der is no difference between manual mapping and automapping

public class Box
{
    public virtual Guid Id { get; set; }
    public virtual IList<Item> Contents { get; protected set; }

    public Box()
    {
        Contents = new List<Item>();
    }

    public void Add(Item item)
    {
        item.Parent = this;
        Contents.Add(item);
    }
}

In automapping you have to make sure the Contents collection is marked inverse either through override or convention and that its keycolumn is the same as the Parent property column. I used to have a convention taht set Inverse() on all collections and override its key column to parent_id

Firo
  • 30,626
  • 4
  • 55
  • 94
  • I was hoping for something a little more elegant given the automapping, but it's looking like this is what I'm going to have to do. Thanks. – James Bender Jan 16 '15 at 18:03
  • NHibernate can't help you here because if it would, you would have a broken model with not yet saved objects. Just think about it if the following would be the case: `var box = new Box { Contents = { someItem } }; someItem.Parent == null` and `var box = new Box { Contents = { someItem } }; session.Save(box); someItem.Parent != null` – Firo Jan 19 '15 at 07:36