c# - 流利的 Nhibernate : Query to retrieve distinct values

标签 c# linq nhibernate fluent-nhibernate

在 DB2 LUW 9.7 数据库上使用 FluentNhibernate 1.3.0.0、NHibernate 3.3.1.4000。

我只想从一个表/实体中获取一些不同的数据。在 SQL 中,这很简单:

select distinct Corporation, CalculationDate, ValuationRule
from MySchema.MyTable
where State == 0

现在,我正在尝试使用 Linq 获取这些数据,但它不起作用...

首先尝试使用选择:

var result = Session.Query<MyEntity>()
        .Where( x => x.State == State.Pending)
        .Select(
           x =>
              new
              {
                 Corporation = x.Corporation,
                 CalculationDate = x.CalculationDate,
                 ValuationRule = x.ValuationRule,
              }).Distinct().ToList();

结果异常:此 SelectClauseVisitor 不支持表达式类型“NhDistinctExpression”。

第二次尝试,使用 Groupby 并只获取键:

var result = Session.Query<MyEntity>()
        .Where( x => x.State == State.Pending)
        .GroupBy(
           x =>
              new
              {
                 Corporation = x.Corporation,
                 CalculationDate = x.CalculationDate,
                 ValuationRule = x.ValuationRule,
              }).Select( x => x.Key).ToList();

结果异常:“无法执行查询”。提示在 select term 中声明的 group by 子句中缺少另一个字段“Model”。这让我很困惑,因为表中存在指定字段,但我不想在该用例中使用该字段...

我错过了什么?

最佳答案

尝试使用 QueryOver...

var result = Session.QueryOver<MyEntity>()
    .Where(x => x.State == State.Pending)
    .SelectList(list => list
        .SelectGroup(x => x.Corporation)
        .SelectGroup(x => x.CalculationDate)
        .SelectGroup(x => x.ValuationRule)               
    )
    .ToList();

如果你想使用不同的:

var result = Session.QueryOver<MyEntity>()
    .Where(x => x.State == State.Pending)
    .SelectList(list => list
                .Select(Projections.Distinct(Projections.Property<MyEntity>(x => x.Corporation)))
                .Select(x => x.CalculationDate)
                .Select(x => x.ValuationRule)
                 )
                .ToList();

关于c# - 流利的 Nhibernate : Query to retrieve distinct values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29848421/

相关文章:

c# - 如何在 linq to NHibernate 中使用 select for associations

c# - NHibernate:传递给 save() 和级联的未初始化代理

c# - 调试IIS随机疯狂内存使用情况

c# - 有什么方法可以在监 window 口中显示/比较对象引用?

c# - session 模式 "ServerState"无法正确处理线程中的 session

c# - 如何让 Windows 窗体应用程序与类(class)一起工作?

c# - 使用 LINQ to Entities 选择最近的记录

c# - linq to xml 中标记的内容

nhibernate - Fluent-Hibernate 存在吗?

c# - 如何在 Fluent-NHibernate 中级联插入父级、子级和组合列表