0
votes

I'm inserting a parent object in the database using Fluent NHibernate, This object have a child, and this child is already persisted in database, but I only have the id from this child.

How can I insert the parent object with his foreign key (child) only setting the id to a child object?

Example:

ObjectParent parent = new ObjectParent();
ObjectChild child = new ObjectChild();

child.Id = 5; // 5 is the id from the child in the database
parent.Child = child;

Service.Create(parent); // here I need to insert the parent with the referenced foreign key (id = 5)

EDIT:

I can't get the child object from the database.

2

2 Answers

1
votes

On the NHibernate level you can use a proxy created by the ISession.

If you can be sure, that the ID (e.g. 5) exists, you can call session.Load<Child>(5). This will return a proxy for you, which in fact do not have to be loaded at all. Inserting that proxy into parent, will issue the INSERT statement only for the Parent

Create(Parent parent, int childId)// = 5)
{

  child = session.Load<Child>(5);

  parent.Child = child;

  session.Save(parent);

Extended:

Another way how to handle references, could be different mapping. I usually use these two properties for Reference and its RefererenceId:

<property not-null="true" name="ChildId" insert="false" update="false" />
<many-to-one name="Child" column="ChildId" />

In your case, solution would be use similar solution, but with updatable ID proeprty

<property not-null="true" name="ChildId" />
<many-to-one name="Child" column="ChildId" insert="false" update="false" />

And the Parent having both properties

class Parent 
{
    public virtual Child Child { get; set; }
    public virtual int ChildId { get; set; }

And the code like

parent.ChildId = 5;
0
votes

Use stateless session as it does not care about relations between (sub) entities by default. It brings real performance improvement, see example within my post.