sql – Nhibernate计数不同(基于多列)
发布时间:2021-01-13 00:13:14 所属栏目:MsSql教程 来源:网络整理
导读:基本上,我一直在尝试这样做(根据两列计算不同): select count(distinct(checksum(TableA.PropertyA,TableB.PropertyB))) from TableA left outer join TableBon TableA.TableBId = TableB.Id where PropertyA like '%123%' 谷歌搜索如何做到这一点,但没有
|
基本上,我一直在尝试这样做(根据两列计算不同): 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);
}
}
>编写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仍然试图找出是否有一种方法来映射函数而无需手动指定参数的数量 (编辑:佛山站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐
热点阅读

