Search code examples
c#.netnhibernatemappingnhibernate-mapping

How do I map to a parent in the same table with NHiberNate using C# (ClassMapping)


I have a following class in which it has a parent of same type,

public class Unit
{
    public virtual int UnitKey { get; set; }
    public virtual string UnitName { get; set; }
    public virtual string UnitType { get; set; }
    public virtual Unit Parent { get; set; }
    public virtual User UnitLeader { get; set; }
}

In the database there is a table called Unit

Unit_Key (int)
Unit_Name (varchar)
Unit_Type (varchar)
Parent_Key (varchar)
User_Key (int)

and here is how Mapping class,

internal class UnitMapping : ClassMapping<Unit>
{
    public UnitMapping()
    {
        Id(x => x.UnitKey, map => 
        { 
            map.Column("Unit_Key"); 
            map.Generator(Generators.Assigned); 
        });
        Property(x => x.UnitName, map => 
        { 
            map.Column("Unit_Name"); 
            map.NotNullable(true); 
        });
        Property(x => x.UnitType, map =>
        {
            map.Column("Unit_Type"); map.NotNullable(true);
        });

        ManyToOne(x => x.UnitLeader, map => 
        { 
            map.Column("User_Key"); map.Cascade(Cascade.None); 
        });
    }
}

How can I map Parent (type of same class) which is in same table.

Thanks


Solution

  • Exactly the same way as you do for a different entity.

    You are already mapping a ManyToOne (UnitLeader); Parent is not different.