1

我正在构建一个端点,以使用 ef 核心从我的数据库中获取最新对象。我的代码是

private AppUser GetLatestUser()
{
  if (context.Roles.Any())
  {
    var max = context.Users.Max(x => x.UpdatedAt);
    return context.Users.Where(x => x.UpdatedAt == max).FirstOrDefault();
  }
  return null;
}
private AppRole GetLatestRole()
{
  if (context.Roles.Any())
  {
    var max = context.Roles.Max(x => x.UpdatedAt);
    return context.Roles.Where(x => x.UpdatedAt == max).FirstOrDefault();
  }
  return null;
}
.....

我想避免对我拥有的每个实体使用几乎相同的代码。想使用类型作为参数,但不知道如何做到这一点。

4

1 回答 1

2

你应该尝试这样的事情

private T GetLatestEntry(T entity) where T : class
{
    return context.Set<T>().OrderByDescending(x => UpdatedAt).FirstOrDefault();
}
于 2019-02-20T14:26:09.577 回答