public async Task<ApiResult> GetId(int id)
{
    if (id <= 0 || id > 9999)
    {
        var data = await _db.ContentNotices
            .Where(x => x.Status == 1)
            .OrderByDescending(x => x.Sort)
            .Select(x => new NoticeInfoRes
            {
                Id = x.Id,
                Time = x.Time.ToString("yyyy-MM-dd"),
                Title = x.Title,
                Content = x.Content
            })
            .FirstOrDefaultAsync();

        return Api.Ok(data);
    }

    var notice = await _notice.GetById(id);

    if (notice == null)
    {
        notice = await _db.ContentNotices
            .Where(x => x.Status == 1)
            .OrderByDescending(x => x.Sort)
            .Select(x => new NoticeInfoRes
            {
                Id = x.Id,
                Time = x.Time.ToString("yyyy-MM-dd"),
                Title = x.Title,
                Content = x.Content
            })
            .FirstOrDefaultAsync();
    }

    return Api.Ok(notice);
}

优化说明:

  1. 使用 Where 替代 FirstOrDefault 的条件判断,可以提高查询效率;
  2. 使用 Select 显式选择需要的字段,避免查询全部字段造成性能浪费;
  3. 将重复的代码抽象成一个变量,避免重复查询数据库。

代码说明:

  • GetId 函数接受一个 id 参数,用于获取相应的通知信息。
  • 如果 id 无效或未找到,则返回状态为 1 的最新通知信息。
  • 函数使用 Where 查询条件筛选出符合要求的通知,并使用 OrderByDescending 按排序字段进行排序。
  • 使用 Select 将查询结果映射到 NoticeInfoRes 对象,避免查询全部字段。
  • 函数最后返回 ApiResult 对象,包含通知信息或错误信息。

优化后的代码更加高效、简洁,避免了重复查询数据库,提高了代码的可读性和可维护性。

Get Notice by Id - API Endpoint

原文地址: https://www.cveoy.top/t/topic/lwLC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录