尝试删除删除带有检查约束的nhibernate集合

时间:2012-03-26 14:41:18

标签: c# sql sql-server nhibernate nhibernate-mapping

SQL Server:

表名:爸爸 字段:Id

表名:妈妈 字段:Id

表名:Child 字段:Id,IdDad,IdMom

子检查约束:IdDad不为null或IdMom不为空

NHibernate映射类

public class ChildBase
{
    public int Id { get; set; }
}

public class DadChild : ChildBase
{
    public int IdDad { get; set; }
}

public class MomChild : ChildBase
{
    public int IdMom { get; set; }
}

public class Dad
{
    public int Id { get; set; }

    // Cascade = All, Table = "Child", ColumnKey = "Id"
    public IList Children { get; set; }

}

如果我在Dad对象中有3个孩子的儿童集合,我删除并删除了孩子

foreach (Child child in Dad.Children)
{
    child.Delete();
}

Dad.Children.Clear();

Data.Flush();

我收到约束违规错误,因为在尝试从Dad中删除子项时,约束表明Child表不能将IdDad和IdMom置为null。

NHibernate尝试做这样的更新:

更新Child set IdDad = null其中Id = xxx

由于IdMom目前为null,不能将IdDad和IdMom null,我如何从NHibernate中删除子集合?

- 编辑 -

<class name="Dad, MyAssembly" table="Dad" lazy="true">
    <id name="Id" access="property" column="Id" type="Int32" unsaved-value="0">
      <generator class="native">
      </generator>
    </id>
    <bag name="Children" access="property" table="Child" lazy="true" cascade="all" >
      <key column="IdDad" />
      <one-to-many class="Child, MyAssembly" />
    </bag>
</class>

1 个答案:

答案 0 :(得分:1)

如果您希望以这种方式删除实体,则应在集合映射上使用inverse="true"

<bag name="Children" access="property" inverse="true" table="Child" lazy="true" cascade="all" >
  <key column="IdDad" />
  <one-to-many class="Child, MyAssembly" />
</bag>

Inverse Attribute in NHibernate