Fluent NHibernate-如何插入子对象而不通过NHibernate获取它

Fluent NHibernate-如何插入子对象而不通过NHibernate获取它,nhibernate,fluent-nhibernate,nhibernate-mapping,Nhibernate,Fluent Nhibernate,Nhibernate Mapping,我正在使用Fluent NHibernate在数据库中插入父对象, 这个对象有一个子对象,并且这个子对象已经在数据库中持久化,但我只有这个子对象的id 如何插入父对象及其外键(子对象)仅将id设置为子对象 例如: ObjectParent parent = new ObjectParent(); ObjectChild child = new ObjectChild(); child.Id = 5; // 5 is the id from the child in the database p

我正在使用Fluent NHibernate在数据库中插入父对象, 这个对象有一个子对象,并且这个子对象已经在数据库中持久化,但我只有这个子对象的id

如何插入父对象及其外键(子对象)仅将id设置为子对象

例如:

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)
编辑:


我无法从数据库中获取子对象

在NHibernate级别,您可以使用由
会话创建的代理

如果可以确定ID(例如5)存在,则可以调用
session.Load(5)
。这将为您返回一个
代理
,实际上根本不需要加载它。将该代理插入父级,将仅为父级发出INSERT语句

代码是这样的

parent.ChildId = 5;

使用,因为默认情况下它不关心(子)实体之间的关系。它带来了真正的性能改进,请参见中的示例。

我无法从数据库中获取子项。我为您提供了另一种方法。这将适用于您,您需要更改映射并在父对象上引入ChildId属性
<property not-null="true" name="ChildId" insert="false" update="false" />
<many-to-one name="Child" column="ChildId" />
<property not-null="true" name="ChildId" />
<many-to-one name="Child" column="ChildId" insert="false" update="false" />
class Parent 
{
    public virtual Child Child { get; set; }
    public virtual int ChildId { get; set; }
parent.ChildId = 5;