Search code examples
nhibernatemany-to-manyone-to-manyone-to-one

NHibernate Many-to-one cascade


I have the below two classes:

public class Project
{

    public virtual int ProjectId { get; set; }
    public virtual string ProjectName { get; set; }
    public virtual LegalEntity LegalEntity { get; set; }
}

and

public class LegalEntity
{
    public virtual int LegalEntId { get; set; }
    public virtual string Name { get; set; }
}

with mappings as:

<class name="Project" table="Project" dynamic-update="true">
  <id name="ProjectId">
    <generator class="native"/>
  </id>  

  <property name="ProjectName" />
  <many-to-one name="LegalEntity" column="LegalEntId" fetch="join" cascade="all-delete-orphan" />


</class>

and

<class name="LegalEntity" table="LegalEnt" dynamic-update="true">

  <id name="LegalEntId">

    <generator class="native"/>

  </id>



  <property name="Name" />    

</class>

In database, Project table has a FK to LegalEntity's PK column. One Project will have only one legal entity. Different projects can have same legal entity. So thats the reason I have gone for many-to-one. Not sure if this is correct though.

Insert and update is working fine. But if I update a legal entity id in a project and that legal entity becomes orphan, I want it to be deleted. But its not happening. Am I wrong in understanding delete-all-orphan? If yes, how can I achieve this behaviour?


Solution

  • The many-to-one cascade does not support all-delete-orphan, see:

    <many-to-one
        ...
        cascade="all|none|save-update|delete"              (4)
        ...
    

    Also, it would be almost impossible to handle this feature by NHibernate's session. Because it does not have to be clear, that the referenced many-to-one is really orphan. There should be some farther checks in DB... there could be other places referencing this table row...

    Suggestion: do it in your code as a part of the DAO or Business Facade implementation. Check if there are really no dependencies, and then issue explicit Delete()

    EXTEND: Here is a QueryOver syntax to get a list of all "orphan" LegalEntity

    // subquery
    var subquery = QueryOver.Of<Project>()
        .Select(x => x.LegalEntity.LegalEntId);
    
    // just these legal entities, which are NOT used
    var query = session.QueryOver<LegalEntity>()
        .WithSubquery
          .WhereProperty(y => y.LegalEntId)
          .NotIn(subquery)
        ;
    
    // orphans
    var list = query
        .List<LegalEntity>();