views:

34

answers:

2

Hello, I'm using Nhibernate with Fluent and I encounter an issue with inheritance.

Here my DB schema

TABLE Base

  • IDBASE (PK)
  • Field1
  • TYPE

TABLE T1

  • IDBASE (PK and FK)
  • Field2
  • Field3 ...

My mapping files are :

public class BaseMap: ClassMap<BASE>
{
    public BaseMap()
    {
        Id(x => x.Id, "IDBASE").GeneratedBy.Identity();

        Map(x => x.Field1);
        DiscriminateSubClassesOnColumn("TYPE");
    }
 }

    public class T1Map: SubclassMap<T1>
    {

        public T1Map()
        {
            Table("T1");
            KeyColumn("IDBASE");
            DiscriminatorValue("T1");

            Map(x => x.Field2).Not.Nullable();
            Map(x => x.Field3).Not.Nullable();
        }
    }

I use FluentMappings instead of AutoMapping.

Here my entities :

public abstract class BASE
{
   public virtual long IdBase{ get; set; }
   public virtual string Field1 { get; set; }
}

public class T1: BASE
{
    public virtual string Field2 { get; set; }
    public virtual string Field3 { get; set; }
}

T1 entity inherits from BASE entity, the issue is when I try to get a row NHibernate try to select Field2 and Field3 on the Base Table whereas they should be selected on T1 Table.

I've tried dozens of hacks but it still doesn't work, if anyone as an idea it would be very helpful.

Thanks a lot.

+1  A: 

You're specifying a discriminator, that implies that the inheritance structure should be a table-per-class-hierarchy; you won't have two tables with this setup, you'll have a single table with everything in (hence why the select is hitting the same table for all the columns).

If you remove the DiscriminateSubclassesOnColumn call, that'll put your mappings into a table-per-class, so you'll have your desired structure.

James Gregory
A: 

Actually I really need the DiscriminateSubclassesOnColumn so I found an other solution, in my inherited entity I do the mapping with the join like this :

public class T1Map: SubclassMap<T1>
{

    public T1Map()
    {
        Join("T1", y =>
        {
            y.KeyColumn("IDBASE");
            y.Map(x => x.Field2).Not.Nullable();
            y.Map(x => x.Field3).Not.Nullable();
        }); 
    }
}

And it works fine, I can keep the Discriminator column on my base class.

Thanks

Webflo

related questions