简体   繁体   中英

Nhibernate Join 2 QueryOver

I can't find how to join two different QueryOver, group by and perform a substraction in the select.

Say you have :

public class EntityA
{
    public virtual int Id;
    public virtual string Reference;
    public virtual int Quantity;
    [Some properties]
}

public class EntityB
{
    public virtual int Id;
    public virtual int EntityAId;
    [Some properties]
}

If i translate my query in pseudo-SQL, i would like to have :

SELECT A.Id, A.Reference, A.Quantity - COALESCE(DERIV_B.TOTAL, 0)
FROM EntityA A
LEFT JOIN (
    SELECT B.EntityAId, COUNT(B.Id) AS TOTAL
    FROM EntityB B
    GROUP BY B.EntityAId) DERIV_B
ON A.Id = DERIV_B.EntityAId
WHERE (A.Quantity - COALESCE(DERIV_B.TOTAL, 0)) >= 0

I can have the subquery on EntityB via QueryOver, but i can't join on EntityA :

var entitiesB = GetCurrentSession().QueryOver<EntityB>().SelectList(select => select.SelectGroup(x => x.EntityAId).SelectCount(x => x.Id));

var entitiesA = GetCurrentSession().QueryOver<EntityA>(). ???

I tried to store the entitiesB in an alias and the perform a JoinAlias on it but i have an exception because it can't retrieve my alias.

Do you have any solution ?

I don't want to create a reference between these two entites.

Short answer is not , you can't do QueryOver if your entities are not connected through model. One solution would be to use NHibernate.Linq and subqueries

var session = GetCurrentSession();
var entityBQuery = session.Query<EntityB>();
var entityAQuery = session.Query<EntityA>()
                          .Select(eA=>new { Id = eA.Id,
                                            Description = eA.Description,
                                            Quantity = eA.Quantity - entityBQuery.Where(eb=>eb.EntityAId = eA.Id).Count()
                                          }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM