Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate entity with multiple Many-To-Many lists of the same type?

Does anybody know how I would map an entity with two many-to-many collections of the same child type.

My database structure is this....

The "normal" relationship will be....

tbl_Parent
  col_Parent_ID

tbl_Parent_Child_Xref
   col_Parent_ID
   col_Child_ID

tbl_Child
   col_Child_ID

The alternative relationship is...

tbl_Parent
  col_Parent_ID

tbl_Include_ParentChild_Xref
   col_Parent_ID
   col_Child_ID

tbl_Child
   col_Child_ID

The entity and mapping look like this...

public partial class ParentEntity : AuditableDataEntity<ParentEntity>
{
  public virtual IList<ChildEntity> Children { get; set; }
  public virtual IList<ChildEntity> IncludedChildren { get; set; }
}

public partial class ParentMap : IAutoMappingOverride<ParentEntity>
{
    public void Override(AutoMapping<ParentEntity> mapping)
    {
        mapping.Table("tbl_Parent");

        mapping.HasManyToMany(x => x.Children)
        .Table("tbl_Parent_Child_Xref")
        .ParentKeyColumn("col_Parent_ID")
        .ChildKeyColumn("col_Child_ID")
        .Inverse()
        .Cascade.All();

        mapping.HasManyToMany(x => x.IncludedChildren)
        .Table("tbl_Include_ParentChild_Xref")
        .ParentKeyColumn("col_Parent_ID")
        .ChildKeyColumn("col_Child_ID")
        .Inverse()
        .Cascade.All();
    }
}

The error that I'm getting is "System.NotSupportedException: Can't figure out what the other side of the many-to-many property 'Children' should be."

I'm using NHibernate 2.1.2, FluentNhibernate 1.0.

like image 967
Rob Gibbens Avatar asked Dec 16 '09 16:12

Rob Gibbens


1 Answers

It seems FNH is confused because you seem to map the same object (ChildEntity) to two different tables, if I'm not mistaken.

If you don't really need the two lists to get separated, perhaps using a discriminating value for each of your lists would solve the problem. Your first ChildEntity list would bind to the discriminationg value A, and you sesond to the discriminating value B, for instance.

Otherwise, I would perhaps opt for a derived class of your ChildEntity, just not to have the same name of ChildEntity.

IList<ChildEntity> ChildEntities
IList<IncludedChildEntity> IncludedChildEntities

And both your objects classes would be identitical.

If you say it works with NH, then it might be a bug as already stated. However, you may mix both XML mappings and AutoMapping with FNH. So, if it does work in NH, this would perhaps be my preference. But think this workaround should do it.

like image 148
Will Marcouiller Avatar answered Nov 16 '22 07:11

Will Marcouiller