2

Let me please explain our situation first.

We are working on a brown field application. There is a given database structure we can't change like this example:

Table1 [ID] [Field1] [Field2] [Field3] ...

Table2 [ID] [Table1_ID] [FieldA] [FieldB] [FieldC] ...

Table1_ID is a foreign key to Table1. This means Table1 can have multiple childs from Table2.

None of the fields and keys can be null. Each table has a pre INSERT trigger setting the ID from its table sequence.

We have the following classes in our application.

Class for database Table1:

public class Parent
{
   public virtual long? Id { get; set; }
   public virtual string Field1 { get; set; }
   public virtual string Field2 { get; set; }
   public virtual string Field3 { get; set; }

   public virtual List<Child> Children { get; set; } // Holds the children of Table2
}

Class for database Table2:

public class Child
{
   public virtual long? Id { get; set; }
   public virtual long? ParentId { get; set; }
   public virtual string FieldA { get; set; }
   public virtual string FieldB { get; set; }
   public virtual string FieldC { get; set; }
}

We need to serialize this tree-structure (this is just the simpliest version) over network. For serialization, we use ServiceStack.Text in ServiceStack.

Due to the fact that a back-reference from Table2 to Table1 as an object would cause a circular reference error when serializing (Table1 -> Table2 -> Table1 -> Table2 ... and so on) we are bound to this structure.

The client/server creates a new structure without setting any Id or ParentId. The key values are NULL. We want NHibernate to do this for us.

Is there a way to create a working Fluent-NHibernate mapping which first inserts Table1, consuming the new Id from the database INSERT trigger, applying this Id to its childrens ParentIds and inserting the children (of Table2)?

It is important not to insert the children without a ParentId and updating the ParentId in a second step.

MVCible
  • 391
  • 3
  • 14
  • While you find an answer, you still can 1) turn of cascading. 2) Save the Parent, call session.Flush(). 3) Now the Parent.ID is in place, call for each over children, assing the ParentId.. and call.Save(child). At the end call the Flush(). In fact, thht's how the cascade is working ;) – Radim Köhler Jan 30 '14 at 11:39

0 Answers0