4

基本上,我一直在尝试这样做(基于两列计算不同):

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

一直在谷歌上搜索如何做到这一点,但没有运气。试过这个,但从未真正奏效。根据两个表中的两个属性,这并不能明确计算:

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();
4

1 回答 1

7

好的,这将采取一些步骤,所以请耐心等待。我在这里假设 SQL 服务器,但说明应该适用于任何支持checksum1的方言:

  1. 创建支持该checksum功能的自定义方言:

    public class MyCustomDialect : MsSql2008Dialect
    {
        public MyCustomDialect()
        {
            RegisterFunction("checksum", new SQLFunctionTemplate(NHibernateUtil.Int32, "checksum(?1, ?2)"));
        }
    }
    
  2. 更新您的配置以使用自定义方言(您可以在配置 XML 文件或代码中执行此操作。有关更多信息,请参阅此答案)。以下是我在现有配置代码中的操作方式:

    configuration
        .Configure(@"hibernate.cfg.xml")
        .DataBaseIntegration(
            db => db.Dialect<MyCustomDialect>());
    
  3. 创建一个调用checksum. 这一步是可选的Projections.SqlFunction——如果你愿意,你可以直接调用,但我认为将它重构为一个单独的函数会更干净:

    public static class MyProjections 
    {
        public static IProjection Checksum(params IProjection[] projections)
        {
            return Projections.SqlFunction("checksum", NHibernateUtil.Int32, projections);   
        }
    }
    
  4. 编写 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仍在试图弄清楚是否有一种方法可以在不手动指定参数数量的情况下映射函数

于 2014-02-12T15:07:01.110 回答