Error in Linq: The text data type cannot be selected as DISTINCT because it is not comparable

六眼飞鱼酱① 提交于 2019-12-12 04:08:29

问题


I've a problem with LINQ. Basically a third party database that I need to connect to is using the now depreciated text field (I can't change this) and I need to execute a distinct clause in my linq on results that contain this field.

I don't want to do a ToList() before executing the Distinct() as that will result in thousands of records coming back from the database that I don't require and will annoy the client as they get charged for bandwidth usage. I only need the first 15 distinct records.

Anyway query is below:

        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);

I know I can do a subquery to do the same thing as above (tSearches contains unique records) but I'd rather a more straightfoward solution if available as I need to change a number of similar queries throughout the code to get this working.


回答1:


No answers on how to do this so I went with my first suggestion and retrieved the unique records first from tSearch then constructed a subquery with the non unique records and filtered the search results by this subquery. Answer below:

        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;


来源:https://stackoverflow.com/questions/9773389/error-in-linq-the-text-data-type-cannot-be-selected-as-distinct-because-it-is-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!