6

我正在尝试使用 Linq-to-NHibernate 获得以下 SQL 输出:

SELECT DISTINCT Name, at.Year FROM MyTable mt
INNER JOIN AnotherTable at ON at.Id = mt.AnotherTableId

Name 和 Year 属性将包含在一个新类中,因此 C# 代码将如下所示:

Session.Linq()
   .Select(x => new FooBar { Name = x.Name, Year = x.AnotherTable.Year }))
   .ToList();

如何让 DISTINCT 关键字出现在 sql 查询中?

4

2 回答 2

1

你不能试试:

Session.Linq()
   .Select(x => new FooBar { Name = x.Name, Year = x.Year }))
   .Distinct()
   .ToList();

Select返回一个IEnumerable,所以默认情况下它应该Distinct,不管你的智能感知是否检测到它。

于 2009-11-16T04:36:47.130 回答
1

我不每天使用 linq 提供程序,但环顾四周似乎是不可能的。

你可以考虑 QueryOver 吗?

 First firstReference = null;
        Second secondReference = null;
        var items = Session().QueryOver(() => firstReference)
                        .JoinAlias(() => firstReference.Seconds, () => secondReference)
                        .Select(Projections.Distinct(
                                Projections.ProjectionList()
                                    .Add(Projections.Property(() => firstReference.Name).WithAlias(() => firstReference.Name))
                                    .Add(Projections.Property(() => secondReference.Year).WithAlias(() => secondReference.Year))))
                        .TransformUsing(Transformers.AliasToBean(typeof(FooBar)))
                        .List<FooBar>();

我希望这有帮助。

于 2011-08-10T20:08:03.217 回答