基本上,我一直在尝试这样做(根据两列计算不同):
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();
解决方法
好的,这需要几步,所以请耐心等待.我在这里假设sql服务器,但是指令应该适用于任何支持checksum1的方言:
public class MyCustomDialect : Mssql2008Dialect { public MyCustomDialect() { RegisterFunction("checksum",new sqlFunctionTemplate(NHibernateUtil.Int32,"checksum(?1,?2)")); } }
>更新您的配置以使用自定义方言(您可以在配置XML文件中或使用代码执行此操作.有关更多信息,请参阅this answer).以下是我在现有配置代码中的使用方法:
configuration .Configure(@"hibernate.cfg.xml") .DataBaseIntegration( db => db.Dialect<MyCustomDialect>());
>创建一个调用校验和的自定义投影.这一步是可选的 – 你可以直接调用Projections.sqlFunction,但我认为将它重构为一个单独的函数更简洁:
public static class MyProjections { public static IProjection Checksum(params IProjection[] projections) { return Projections.sqlFunction("checksum",NHibernateUtil.Int32,projections); } }
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>();
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 */