首页 > 解决方案 > 如何按嵌套集合最大属性排序

问题描述

我有一个Users表,每个表可能有很多LogActivity,所以是一对多的关系。我想通过 LogActivities 的最大属性 DateSearch 对用户集合进行排序(换句话说,具有最早 LogActivities 的用户将位于顶部)。但是 LogsActivity 的集合可能是空的。另一个要求是用户应该保持 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; }
}

标签: c#linqsql-order-by

解决方案


看起来您在从数据库中转换检索到的数据时遇到问题。

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

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


推荐阅读