Search code examples
c#asp.netnhibernatefluent-nhibernate-mappingnhibernate-inheritance

NHibernate JOIN mapping fails when the mapped field is moved to a base class


Having two model classes with many common fields, I decided to create a base class and both of them to inherit from it.

The existent model classes already came with map classes.

All the common fields which are now inherited in the child classes are virtual to keep NHibernate happy and they are all mapping alright, except for one...

This my case:

public class BaseClass : EntityBase<Guid>
{
   //This is not complaining 
   public virtual string Text { get; set; }

   //This is complaining
   public virtual Guid TouchGuid { get; set; }
}

public class A : BaseClass
{
    //inherited + specific stuff
}

public class B : BaseClass
{
    //inherited + specific stuff
}

Now these are the mapping classes:

public class AMap : ClassMapping<A>
{
    //Mapping the ID inherited from EntityBase class
    Id(x => x.Id, mapper =>
    {
        mapper.Generator(Generators.GuidComb);
        mapper.Column("Pk_MenuItemId");
    });

    //Mapping the common field inherited, doesn't complain !
    Property(x => x.Mnemonic);

    //This is the one which is complaining, keep in mind it was working
    //before creating the base class and move the TouchGuid property in it.
    Join("Touch", x =>
    {
        x.Key(k =>
        {
            k.Column("EntityId");
            k.ForeignKey("PK_AClassId");
            k.OnDelete(OnDeleteAction.Cascade);
            k.Unique(true);
        });
        x.Property(p => p.TouchGuid);
    });
}

public class BMap : ClassMapping<B>
{
    //Same map as for class A
}

Whenever I run the program, loading the data from those classes (tables), will fail saying it couldn't find the TouchGuid column on the A table respectively B table, here is the error:

enter image description here

Yes, there is common data between A and B tables but I can't change the db scheme, it would add too much complexity now.

Do I need to create a table for the base class too ? I would like to avoid created a new table if possible.

Any hints of what could be wrong ?

Thank you !


Solution

  • I believe NHibernate assumes a DB schema with multiple tables because it defaults to implicit polymorphism mode. Try setting polymorphism=explicit in the mappings.