表每个子类继承映射由NHibernate映射代码

时间:2012-02-05 12:03:29

标签: nhibernate inheritance nhibernate-mapping mapping-by-code

如何在这个类的每个子类策略的新NHibernate Mapping-By-Code中编写映射:

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; }
}

1 个答案:

答案 0 :(得分:7)

这是一种可能的缩略形式的映射

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);
    }
}

您不需要在派生类中复制Id属性的声明。它继承自父Person类。