user981375
user981375

Reputation: 647

NHibernate: how to select parent with single child (knowing childID)?

  1. I want to add child to a parent. At which point is the new ID of a child known to me? Can I access it before DB insert? My ID generator is HILO. The reason I'm asking is that copy of the parent object needs to be propagated to another app. Knowing this would would potentially save me a trip to DB just to discover what the ID of newly inserted Child is as I have all the other info already available to me.

  2. If 1) can not be accomplished w/out roundtrip to a DB then (after an insert) how can I select parent with child only? Parent may have multiple children but I'm only interested in a parent with that child only. This is not quite working for me:

    parent = session.QueryOver() .List() .Where(p => p.Children.Select(c => c.Id == ChildId).First()).First();

SQL equivalent I want is:

select Parent.Id, Children.* From Parent
    join Children on Parent.Id = Children.ParentId
    where ChildId = 1540096

Upvotes: 0

Views: 123

Answers (1)

Newbie
Newbie

Reputation: 7249

On Session.Save(YourObject) the ID will populated for your object. However, this will not result in a immediate insert to the database. The actual insert will take place on session flush (Transaction.Commit, etc).

That aside, with your current approach, you may propagate an Id that may not map to an existing object. For example, imagine you propagate an Id before the insert and then your insert fails for whatever reason. How are gonna deal with this inconsistent state? Beware of this case and similar ones.

My advice to you is to not propagate state that may be invalid.

Upvotes: 1

Related Questions