4

How to write mappings in new NHibernate Mapping-By-Code in Table Per Subclass strategy for this classes:

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

public class JuridicalPerson : Person
{
    public virtual int Id { get; set; }
    public virtual string LegalName { get; set; }
}

public class PrivatePerson : Person
{
    public virtual int Id { get; set; }
    public virtual bool Sex { get; set; }
}
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
Serg Melikyan
  • 369
  • 1
  • 5
  • 7
  • 2
    Have a look here: http://notherdev.blogspot.com/2012/01/mapping-by-code-inheritance.html for all inheritance-related options in mapping-by-code. – NOtherDev Feb 05 '12 at 15:48

1 Answers1

8

Here is a possible mapping in a slighly abbreviated form

public class PersonMapping : ClassMapping<Person>
{
    public PersonMapping()
    {
        Table("person");
        Id(x => x.Id, m => m.Generator(Generators.Native));
        Property(x => x.Name);
    }
}

public class JuridicalPersonMapping : JoinedSubclassMapping<JuridicalPerson>
{
    public JuridicalPersonMapping()
    {
        Table("juridical_person");
        Key(m => m.Column("person_id"));
        Property(x => x.LegalName);
    }
}

public class PrivatePersonMapping : JoinedSubclassMapping<PrivatePerson>
{
    public PrivatePersonMapping()
    {
        Table("private_person");
        Key(m => m.Column("person_id"));
        Property(x => x.Sex);
    }
}

You don't need to duplicate declaration of the Id property in the derived classes. It's inherited from the parent Person class.

hival
  • 675
  • 4
  • 5
  • I know this post is veeery old. But may you tell me how the database tables should look like? –  Dec 19 '18 at 15:00