如何使用LINQ to实体对不在数据库中的列进行排序?

时间:2011-02-25 21:02:15

标签: linq entity-framework

LINQ to Entities 3.5不支持String.Join所以我将gridview绑定到我在Select语句之外定义的属性。显然它不会让我对RecipientNames进行排序,因为它只是一个IEnumerable而且没有意义。如何使用LINQ to Entities对我的新列进行排序?如果可能的话,我想完全摆脱RecipientNamesList并创建一些LINQ将能够处理的东西。

IQueryable<NotificationDetail> resultsFlattened = results.Select(n => new NotificationDetail() 
{
..
RecipientNames = n.NotificationRecipients.Select(nr => nr.Recipient.RecipientNameFirst + " " + nr.Recipient.RecipientNameLast).Where(s => s.Trim().Length > 0)});
});

IQueryable<NotificationDetail> resultsPaged = ApplySortingPaging(resultsFlattened,SortPageOptions);

return resultsPaged.ToEntityList(results.Count()); //blows up here, obviously

public string RecipientNamesList
{
    get
    {
          return String.Join(", ", RecipientNames.ToArray());
    }
}

1 个答案:

答案 0 :(得分:0)

它爆炸,因为排序无法转换为SQL。简单的解决方案是确保在本地而不是在SQL Server中执行排序。只需在第一次查询后添加ToListAsEnumerable

resultsFlattened = resultsFlattened.ToList(); 

您需要确保在此之前进行分页,否则您可能会从数据库中删除大量行。


或者您使用Damien Guard和其他人开发的Linq.Translations库。它使您可以根据需要使用本地计算属性。