Reputation: 689
SQL Server:
Table Name : Dad Fields: Id
Table Name : Mom Fields: Id
Table Name: Child Fields: Id, IdDad, IdMom
Child Check Constraint: IdDad is not null or IdMom is not null
NHibernate mapping class
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; }
}
If i have in Dad object a Children collection with 3 Children i remove and delete the children
foreach (Child child in Dad.Children)
{
child.Delete();
}
Dad.Children.Clear();
Data.Flush();
i get the constraint violation error because when trying to remove the children from Dad, the constraint says that the Child table cannot have IdDad and IdMom at null.
NHibernate try to do an update like this:
Update Child set IdDad = null where Id = xxx
As IdMom is currently null, can't be IdDad and IdMom null, how can i delete from NHibernate the children collection?
-EDIT-
<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>
Upvotes: 0
Views: 832
Reputation: 15303
You should use inverse="true"
on your collection mapping if you wish to delete the entities in this manner.
<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
Upvotes: 1