【问题标题】:Error in Linq: The text data type cannot be selected as DISTINCT because it is not comparableLinq 中的错误:无法将文本数据类型选为 DISTINCT,因为它不可比较
【发布时间】:2012-03-19 15:51:26
【问题描述】:

我对 LINQ 有疑问。基本上,我需要连接的第三方数据库正在使用现已折旧的文本字段(我无法更改此字段),并且我需要在我的 linq 中对包含此字段的结果执行不同的子句。

我不想在执行 Distinct() 之前执行 ToList(),因为这会导致数以千计的记录从我不需要的数据库中返回,并且会在客户收取带宽费用时惹恼他们用法。我只需要前 15 条不同的记录。

无论如何查询如下:

        var query = (from s in db.tSearches
                     join sc in db.tSearchIndexes on s.GUID equals sc.CPSGUID
                     join a in db.tAttributes on sc.AttributeGUID equals a.GUID
                     where s.Notes != null && a.Attribute == "Featured" 
                     select new FeaturedVacancy
                     {
                         Id = s.GUID,
                         DateOpened = s.DateOpened,
                         Notes = s.Notes
                     });
        return query.Distinct().OrderByDescending(x => x.DateOpened);

我知道我可以做一个子查询来做与上面相同的事情(tSearches 包含唯一记录),但如果可用,我宁愿一个更直接的解决方案,因为我需要在整个代码中更改许多类似的查询来获得这个工作。

【问题讨论】:

  • 您是否考虑过按唯一 GUID 进行分组?
  • 即使这会以某种方式运行,您的查询也不会表达应该不同的内容,因为最终结果中的 Notes 集合。也许你可以通过它的导航属性(如果它们存在的话)查询Notes并表达条件,从而生成包含EXISTS子句的SQL,并产生不同的Notes而没有Distinct语句。

标签: c#-4.0 .net-4.0 linq-to-entities


【解决方案1】:

没有关于如何执行此操作的答案,因此我采用第一个建议并首先从 tSearch 检索唯一记录,然后使用非唯一记录构造一个子查询,并通过该子查询过滤搜索结果。答案如下:

        var query = (from s in db.tSearches
                     where s.DateClosed == null && s.ConfidentialNotes != null
                     orderby s.DateOpened descending
                     select new FeaturedVacancy
                     {
                         Id = s.GUID,
                         Notes = s.ConfidentialNotes
                     });

        /* Now filter by our 'Featured' attribute */
        var subQuery = from sc in db.tSearchIndexes
                       join a in db.tAttributes on sc.AttributeGUID equals a.GUID
                       where a.Attribute == "Featured"
                       select sc.CPSGUID;

        query = query.Where(x => subQuery.Contains(x.Id));

        return query;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多