简体   繁体   中英

Fluent Nhibernate - Mapping hierarchy

Im using nhibernate on my project and I have a table of soldiers:

ID, FIRSTNAME, LASTNAME, COMMANDERID

So every soldier has a commande whicn is also a soldier.

I have the class Soldier:

    public class Soldier
    {
        public virtual int Id { get; set;}
        public virtual Soldier Commander { get; set; }
        public virtual IList<Soldier> Soldiers { get; set; }
    }

My question is, how do I map the Soldiers property? I tried the following :

HasMany(x => x.Soldiers).KeyColumn("COMMANDERID");

But im getting an exception.

What you have here is a one-to-many relationship with the class itself (instead of another class). So I believe you must have both "Reference" and "HasMany" specified in your mapping in the class Soldier. Thus, I think the correct map for the class Soldier would be something like this:

Table("Soldier");
Id(x => x.ID).GeneratedBy.Identity();
Map(x => x.FIRSTNAME);
Map(x => x.LASTNAME);
Reference(x => x.Commander).Column("COMMANDERID"); //Parent
HasMany(x => x.Soldiers).Cascade.All().Inverse().KeyColumn("COMMANDERID"); //Children

Not really sure about how Inverse and Cascade will work, once we are talking about the same entity. You may probably need to test it.

This other question may also help you to solve your problem (the scenario in very similar): Fluent / NHibernate Collections of the same class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM