Search code examples
mysqlnhibernatequeryover

NHibernate + QueryOver: How to join unmapped entity by ID?


given is the table A with columns EntityType (Enum that specifies either Entity/Table of type B or Entity/Table of type C) and EntityID (ID of an entry in table B or table C).

Both classes B and C implement interface IBC and class A has a property IBC.

This works, but when I have one A and access property IBC it will do one more query to select the row of either table B or C. If I have a lot of A's it will do a lot of queries.

I want to do this query with NHibernate QueryOver so that there will be no more additional queries:

select * from A a left join B b on b.ID = a.EntityID left join C c on c.ID = a.EntityID

Is there any possibility?

Thank you.


Solution

  • Check the latest feature of NH 5.0

    17.5. Join entities without association (Entity joins or ad hoc joins)

    small cite:

    In QueryOver you have the ability to define a join to any entity, not just through a mapped association. To achieve it, use JoinEntityAlias and JoinEntityQueryOver. By example:

    Cat cat = null;
    Cat joinedCat = null;
    
    var uniquelyNamedCats = sess.QueryOver<Cat>(() => cat)
        .JoinEntityAlias(
            () => joinedCat,
            () => cat.Name == joinedCat.Name && cat.Id != joinedCat.Id,
            JoinType.LeftOuterJoin)
        .Where(() => joinedCat.Id == null)
        .List();