views:

115

answers:

1

I'm having some trouble getting NH to persist my object graph.

I have (something like) this:

/*Tables*/
TABLE Parent
  ParentID PK 
  LastEventID NULL

TABLE Event
  EventID PK
  ParentID FK NOT NULL


//Model Classes

public class Parent
{
    public List<Event> Events;  //Inverse

    //Denormalized bit
    public Event LastEvent;  //not inverse

}

public class Event
{
    public Parent Parent;  //Makes the association up there Inverse
}

I'm creating a new Parent, creating a new Event, adding the new Event to Parent.Events and setting Parent.LastEvent to the new Event.

When I tell NH to save the Parent I get an error about a transient object needing to be saved first. I assume its because the association between Parent and Event is not clear.

The way the SQL needs to go is to insert the Parent with a null LastEvent, then insert the Event, then update Parent.LastEvent.

So how do I get NH to do this?

A: 

Without seeing your mapping schema, I'll have to guess.

Are you cascading your updates? From the reference:

To save or update all objects in a graph of associated objects, you must either

  • Save(), SaveOrUpdate() or Update() each individual object OR
  • map associated objects using cascade="all" or cascade="save-update".

Assuming you don't already have this, does adding cascade="all" or cascade="save-update" to the side marked inverse="true" fix the problem?

Stuart Childs
Yes, that helped. It turns out the real scenario is more complicated (this was a simplification of what seemed to be the problem area.) The immediate problem was solved by exactly what you described though.
brendanjerwin