Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

NHibernate Pitfalls: Non Nullable Columns in Table Per Class Hierarchy Inheritance

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

When you use the Table Per Class Hierarchy inheritance mapping pattern (Single Table Inheritance in Martin Fowler’s terminology), all properties of derived classes should map to nullable columns in the database. If that is not the case, it won’t be possible to insert any records of any class, because of the required columns that are not present in that class, and you will get an constraint violation error.

For example:

   1: public class PersonMapping : ClassMapping<Person>
   2: {
   3:     public PersonMapping()
   4:     {
   5:         this.Table("`PERSON`");
   6:         this.Lazy(true);
   7:  
   8:         this.Id(x => x.PersonId, x =>
   9:         {
  10:             x.Column("`PERSON_ID`");
  11:             x.Generator(Generators.HighLow);
  12:         });
  13:  
  14:         this.Property(x => x.Name, x =>
  15:         {
  16:             x.Column("`NAME`");
  17:             x.NotNullable(true);
  18:             x.Length(100);
  19:         });
  20:  
  21:         this.Property(x => x.Gender, x =>
  22:         {
  23:             x.Column("`GENDER`");
  24:             x.NotNullable(true);
  25:             x.Type<EnumType<Gender>>();
  26:         });
  27:     }
  28: }
  29:  
  30: public class NationalCitizenMappping : SubclassMapping<NationalCitizen>
  31: {
  32:     public NationalCitizenMappping()
  33:     {
  34:         this.DiscriminatorValue("NATIONAL_CITIZEN");
  35:         this.Lazy(true);
  36:  
  37:         this.Property(x => x.NationalIdentityCard, x =>
  38:         {
  39:             x.Column("`NATIONAL_IDENTITY_CARD`");
  40:             x.Length(20);
  41:             x.NotNullable(false);
  42:         });
  43:     }
  44: }

Comments

No Comments