Nhibernate counter is different (based on multiple columns)

Basically, I tried to do this (the count is different from the two columns):

select count(distinct(checksum(TableA.PropertyA, TableB.PropertyB))) 
from TableA 
left outer join TableB
on TableA.TableBId = TableB.Id 
where PropertyA like '%123%'

There was a trip to the game, how to do it, but no luck. Tried this but never worked. This is not taken into account based on two properties from two tables:

var queryOver = c.QueryOver<TableA>();
TableB tableBAlias = null;
TableA tableAAlias = null;
ProjectionList projections = Projections.ProjectionList();

queryOver.AndRestrictionOn(x => x.PropertyA).IsLike("%123%");
projections.Add(Projections.CountDistinct(() => tableAAlias.PropertyA));

queryOver.JoinAlias(x => x.TableB , () => tableBAlias, JoinType.LeftOuterJoin);
projections.Add(Projections.CountDistinct(() => tableBAlias.PropertyB));

queryOver.Select(projections);
queryOver.UnderlyingCriteria.SetProjection(projections);
return queryOver.TransformUsing(Transformers.DistinctRootEntity).RowCount();
+3
source share
1 answer

Ok, it takes a few steps, so carry me. I assume the SQL server is here, but the instructions should work for any dialect that supports checksum 1 :

  • Create a custom dialect that supports the function checksum:

    public class MyCustomDialect : MsSql2008Dialect
    {
        public MyCustomDialect()
        {
            RegisterFunction("checksum", new SQLFunctionTemplate(NHibernateUtil.Int32, "checksum(?1, ?2)"));
        }
    }
    
  • , ( , . . ), :

    configuration
        .Configure(@"hibernate.cfg.xml")
        .DataBaseIntegration(
            db => db.Dialect<MyCustomDialect>());
    
  • , checksum. - Projections.SqlFunction , , , :

    public static class MyProjections 
    {
        public static IProjection Checksum(params IProjection[] projections)
        {
            return Projections.SqlFunction("checksum", NHibernateUtil.Int32, projections);   
        }
    }
    
  • QueryOver :

    int count = session.QueryOver<TableA>(() => tableAAlias)
        .Where(p => p.PropertyA.IsLike("%123%"))
        .Left.JoinQueryOver(p => p.TableB, () => tableBAlias)
        .Select(
            Projections.Count(
                Projections.Distinct(
                MyProjections.Checksum(
                    Projections.Property(() => tableAAlias.PropertyA),
                    Projections.Property(() => tableBAlias.PropertyB)))))
        .SingleOrDefault<int>();
    

    SQL, , :

    SELECT count(distinct checksum(this_.PropertyA, tableba1_.PropertyB)) as y0_
    FROM   [TableA] this_
        left outer join [TableB] tableba1_
        on this_.TableBId = tableba1_.Id
    WHERE  this_.PropertyA like '%123%' /* @p0 */
    


1 ,
+6

All Articles