添加具有一对一子项的父项实例

Adding instance of Parent with one-to-one Child

我有一个父项 class,Parent,它与一个子项 class,Child.

具有一对一的关系

当我添加一个新的Parent时,我想同时在parent上添加一个Child。

以下是我的 classes:

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

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

我正在使用 NHibernate 和此处概述的 HasOne/一对一映射: https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-mapping

下面是我的 AddParentRequestHandler 中的 Handle() 方法的代码:

var parent= new Parent();

var child = new Child()
{
    Parent = parent;
};

parent.Child = child;

session.Save(parent);

执行此操作时出现以下错误: 无法将值 NULL 插入列 'ChildId'、table 'dbo.Parent';列不允许空值。 INSERT 失败。`

Parent 的 ChildId 和 Child 的 ParentId 都是不可空字段。

有什么方法可以解决这个问题并仍然保持这些字段不可为空吗? 提前致谢。

When I add a new Parent, I want to add a Child onto the parent at the same time.

您需要做的就是将 'Child' 对象作为变量存储在 'Parent' class 中,并在 'Parent' 中创建 'Child' 的新实例=]构造函数

private Child child;

public Parent (){
    ...
    child = new Child();
}

我需要做两件事来解决这个问题。

首先,我从架构中的 Parent table 中删除了 ChildId 列。

然后,我将 session.Save 移动到分配 child:

的代码上方
var parent= new Parent();

session.Save(parent);

parent.Child = new Child
{
    Parent = parent;
};

所以现在我没有任何可为空的 Id 字段,并且可以将 parent 与 child 保持一致。