gpt4 book ai didi

c# - 如何将此 Linq 写入 NHibernate 查询

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:41 24 4
gpt4 key购买 nike

我们有这样一个实体:

public class File{
public int Region{get;set;}
public bool ShowLocation{get;set;}
//Other fields are omitted
}

我想写这个查询:

    SELECT Region,SUM(CASE WHEN ShowLocation=1 THEN 1 ELSE 0 END) AS
ShowCount,SUM(CASE WHEN ShowLocation=0 THEN 1 ELSE 0 END) AS NotShowCount
--WHERE omitted for the sake of simplicity
GROUP BY Region

出于某些原因,我想使用 Linq To Nhibernate(我们有一个生成 Expression<Func<File,bool>> 的复杂过滤机制)

到目前为止,我找不到使用 Linq To NHibernate 实现此目的的任何方法。这是我的一些尝试:

Conditioanl Count:(没有异常(exception),但它仍然计算所有行)

    Files
.Where(whereExpression)
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
ShowCount=x.Count(f=>f.ShowLocation==1),
NotShowCount=x.Count(f=>f.ShowLocation==0)
});

条件总和:不支持/实现异常

Files
.Where(whereExpression)
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
ShowCount=x.SUM(f=>f.ShowLocation==1?1:0),
NotShowCount=x.SUM(f=>f.ShowLocation==0?1:0)
});

SELECT Before GROUP : 不支持/实现异常

    Files.Where(whereExpression).Select(x=>new
{
x.Region,
Show=x.ShowLocation==1?1:0,
NotShow=x.ShowLocation==0?1:0
})
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
ShowCount=x.SUM(f=>f.Show),
NotShowCount=x.SUM(f=>f.NotShow)
});

UNION:不支持/实现异常

    Files
.Where(whereExpression)
.Where(x=>x.ShowLocation==1)
.Select(x=>new
{
x.Region,
Show=1,NotShow=0
})
.Union(Files
.Where(whereExpression)
.Where(x=>x.ShowLocation==0)
.Select(x=>new
{x.Region,
Show=0,
NotShow=1
}))
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
CountShow=x.Count(a=>a.Show),
CountNotShow=x.Count(a=>a.NotShow)
});

我没有其他线索。还有其他想法吗?

最佳答案

我不知道您能否让它与 Linq to NH 一起使用。您可以改用 QueryOver 吗? QueryOver API 也接受 Expression<Func<T,bool>>。在 where 子句中,因此您应该能够让它像这样与您现有的过滤器一起工作:

            MyDto dto = null;

var myDtoList = session.QueryOver<File>()
.Select(
Projections.Group<File>(x => x.Region).WithAlias(() => dto.Region),
Projections.Sum(
Projections.Conditional(
Restrictions.Where<File>(c => c.ShowLocation== 1),
Projections.Constant(1),
Projections.Constant(0))).WithAlias(() => dto.ShowCount),
Projections.Sum(
Projections.Conditional(
Restrictions.Where<File>(c => c.ShowLocation== 0),
Projections.Constant(1),
Projections.Constant(0))).WithAlias(() => dto.NotShowCount))
.TransformUsing(Transformers.AliasToBean<MyDto>())
.List<MyDto>();

QueryOver 并不真正适用于匿名类型,因此您必须定义 MyDto使用您要返回的属性,即 Region , ShowCountNotShowCount

关于c# - 如何将此 Linq 写入 NHibernate 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29915325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com