如何通过嵌套集合最大属性排序

时间:2019-01-24 09:20:19

标签: c# linq sql-order-by

我有一个包含Users的表,每个表可能都有许多LogActivity,因此存在一对多关系。我想按LogActivities的最大属性DateSearch对用户集合进行排序(换句话说,最早使用LogActivities的用户将在顶部)。但是LogsActivities的集合可能为空。另一个要求是用户应该保持为IQuerable,这很重要,因为它的性能。

  

“无效的操作专有权:读取数据库值时发生异常。预期的类型为'System.DateTime',但实际值为'System.String'类型”“)和警告(” LINQ表达式'“ Max ()“'无法翻译,将在本地进行评估。”

//(ToListAsync just for testing \\ identities is IQuerable<User>)

//(defaultLogsActivity is LogActivity with DateSearch = DateTime.MinValue)
var qwe = await identities.OrderBy(u => u.LogsUserActivity.DefaultIfEmpty(defaultLogsActivity))
                                .ToListAsync();// => exception("Expression of type 'UserService.Data.TDO_Models.ManagerUsers.LogsUserActivityEntity' cannot be used for parameter of type 'Microsoft.EntityFrameworkCore.Storage.ValueBuffer' of method DefaultIfEmpty")

var qwe = await identities.OrderBy(u => (u.LogsUserActivity.Count != 0) ? u.LogsUserActivity.Max(l => l.DateSearch) : DateTime.MinValue )
                                .ToListAsync(); //=> exception ("Invalid operation excpetion: An exception occurred while reading a database value. The expected type was 'System.DateTime' but the actual value was of type 'System.String'") and warnings ("The LINQ expression '"Max()"' could not be translated and will be evaluated locally.")


 public class User{
    public Guid Id { get; set; }
    public List<LogActivity> LogActivities { get; set; }
} 

public class LogActivity{
   public DateTime DateSearch { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您似乎在转换从数据库检索的数据时遇到问题。

您可以尝试将模型[Timestamp][Column(TypeName = "datetime")]添加到模型中

它应该可以解决您的问题。

相关问题