How to implement .ChildWhere() mapping with many-to-many relation in NH 3.2

617 Views Asked by At

I have following FNH mapping:

public class ItemMap : ClassMap<Item>
{
   public ItemMap ()
   {
       this.HasManyToMany(a => a.ChildItems).ChildWhere("IsDeleted = 0").AsSet();
   }
}

Result hbm file is:

<hibernate-mapping>
  <class name="Item" table="Item">
    <set name="ChildItems" table="ItemsToChildItems">
      ...
      <many-to-many class="ChildItem" where="IsDeleted = 0">
        <column name="ChildItemId" />
      </many-to-many>
    </set>
  </class>
</hibernate-mapping>

I want to implement the same mapping using "sexy mapping by code feature :-) / conformist approach" of NHibernate 3.2

Note: Following approach doesn't work:

public class ItemMap : ClassMapping<Item>
{
   public ItemMap()
   {
      this.Set(x => x.ChildItems
      , map =>
      {
         map.Where("IsDeleted = 0");
      }
      , action => action.ManyToMany());
   }
}

Because: It is following FNH mapping:

public class ItemMap : ClassMap<Item>
{
   public ItemMap ()
   {
      this.HasManyToMany(a => a.ChildItems).Where("IsDeleted = 0").AsSet();
   }
}

.Where("IsDeleted = 0") and .ChildWhere("IsDeleted = 0") not the same.

HBM differences:

Result hbm file using .ChildWhere("IsDeleted = 0") is:

<hibernate-mapping>
  <class name="Item" table="Item">
    <set name="ChildItems" table="ItemsToChildItems">
      ...
      <many-to-many class="ChildItem" where="IsDeleted = 0">
        <column name="ChildItemId" />
      </many-to-many>
    </set>
  </class>
</hibernate-mapping>

Result hbm file using .Where("IsDeleted = 0") is:

<hibernate-mapping>
  <class name="Item" table="Item">
    <set name="ChildItems" table="ItemsToChildItems" where="IsDeleted = 0">
      ...
      <many-to-many class="ChildItem">
        <column name="ChildItemId" />
      </many-to-many>
    </set>
  </class>
</hibernate-mapping>

Who have a similar problem or can offer a solution? Need help.

1

There are 1 best solutions below

0
On

i had the same problem and I found a solution:

https://nhibernate.jira.com/browse/NH-2997

Solution in 3 steps:

1) Add new interface method to IManyToManyMapper interface:

public interface IManyToManyMapper : IColumnsMapper {
void Where(string sqlWhereClause); }

2) Implement new method in ManyToManyCustomizer class:

public void Where(string sqlWhereClause) { customizersHolder.AddCustomizer(propertyPath, (IManyToManyMapper x) => x.Where(sqlWhereClause)); }

3) Implement new method in ManyToManyMapper class:

public void Where(string sqlWhereClause) { manyToMany.where = sqlWhereClause; }