Search code examples
c#inheritancenhibernatenhibernate-mappingnhibernate-mapping-by-code

How to make nhibernate not combine results from inherited objects?


I have a problem with nhibernate queries. The result i get back is a mix from two tables. How do i tell nhibernate not to combine the result from the different tables.

This is my query:

using (var session = SessionFactory.OpenSession())
{
   using (var transaction = session.BeginTransaction())
   {
      timeEntryReportIds = session.Query<XXXX>()
                .Where(x => x.SentToServiceLeader == true && x.StartDate < cutoffDate)
                .Select(x => x.Id)
                .ToList();
      transaction.Commit();
   }
}

My XXXX class mapping looks like this:

public class XXXXMapping : ClassMapping<XXXXEntity>
{
    public XXXXMapping()
    {
        Table("XXXX");
        Property(x => x.X1, c => c.Type<UtcDateTimeType>());
        Property(x => x.X2, c => c.Type<UtcDateTimeType>());
        Property(x => x.X3, c => c.Index("IX_X3"));
        Property(x => x.X4, c => c.Index("IX_X4"));
        Property(x => x.X5);
        Property(x => x.X6);
    }
}

And i have another one that looks like this:

public class YYYYYMapping : ClassMapping<YYYYYEntity>
...

My classes are defined like this:

public class XXXXEntity : MwlEntityBase
...

and

public class YYYYEntity : XXXXEntity
...

The problem i have is that when i run my query i get the result from both the XXXX and YYYYY table. How do i tell nhibernate to not do that!

I did some research before coming here and it told me that i needed to extend the baseclass, but i have no control over the [MwlEntityBase] class. The other classes i have control over. I tried to change Classmapping inheritance from ClassMapping to UnionSubclassMapping and JoinedSubclassMapping. But it failed when starting us saying something about a missing root element or something like that. I assumed that it was because i cant change the MwlEntityBase class? Or it could be that i did things wrong.

Anyway, I need help with the correct way to solve this. I can even settle for a incorrect way to solve this, it it works :)


Solution

  • The short answer, don't inherit from XXXX^^ Just create a abstract base class and derive XXXX and YYYY from this base class.

    public abstract class BaseEntity : MwlEntityBase
    {
        // The common properties for XXXX and YYYY.
    }
    
    public class XXXX : BaseEntity {}
    
    public class YYYY : BaseEntity {}