Warm tip: This article is reproduced from serverfault.com, please click

c#-按日期排序 LINQ 查询中的时间中断

(c# - Order By Date Time breaks in LINQ query)

发布于 2021-10-20 15:41:55

以下详细说明了我收到的错误 The Student Class

public class Student () {
    public int Id {get;set;}
    public Student(int id IEnumerable<StudentOwner> owner) {
         _owners = owners != null ? owners.ToList() : new List<StudentOwner>();
    }
    private List<StudentOwner> _owners;
}

StudentDetails 类

public class StudentDetails () {
    pubiic int Id {get; set;}
    public DateTime UpdateDate { get; }
    public string Comments { get; set; }
    public int StudentRef {get; set; }

}

查询的违规代码选择如下,如果你按 s.ID 订购,则可以使用

  baseQuery = baseQuery.Where(
              o => s.StudentDetails
                   .OrderByDescending(s => **s.UpdateDate**).First().StudentRef
                == StudentSearchParams.StudentRef;

发生以下错误,但是如果你按 Id 进行排序,它可以工作,但不会产生所需的结果。有任何想法吗 ???

 .OrderByDescending(s1 => s1.UpdateDate)' could not be translated. 
 Additional information: Translation of member 'UpdateDate' on entity type 'StudentDetails' failed. 
 This commonly occurs when the specified member is unmapped. Either rewrite the query in a form 
 that can be translated, or switch to client evaluation explicitly by inserting a call to 
 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
Questioner
Welsh King
Viewed
0
Ivan Stoev 2021-10-20 23:56:00

错误信息告诉你

实体类型“StudentDetails”上的成员“UpdateDate”翻译失败。这通常发生在指定成员未映射时

而你所拥有的是

public class StudentDetails
{
    public DateTime UpdateDate { get; }
}

只获取属性(没有设置器)。通过 EF Core 约定

按照惯例,所有带有 getter 和 setter 的公共属性都将包含在模型中。

换句话说,带有 oa 设置器的属性将被忽略(不包括在内,未映射)。

附加set;之后get;,问题就会消失。