Entity Framework Core Automapper 特定用户最近查看的项目

Entity Framework Core Automapper latest viewed items for a specific user

使用 Entity Framework Core,我想获得用户最近查看的 10 个职位的列表。

我正在开发包含 UserJobUserJobView 类.

的 CRM
public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class Job
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

public class UserJobView
{
    public Guid Id { get; set; }
    public Guid JobId { get; set; }
    public Guid UserId { get; set; }
    public DateTime LastViewedAt { get; set; }

    public Job Job { get; set; }
}

我还有一个 JobDto,我打算使用 AutoMapper

public class JobDto : IMapFrom<Job>
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime? LastViewedAt { get; set; }
}

每次 User 查看 Job 我更新或创建一个 UserJobView 对象设置 LastViewedAt 属性 为 DateTime.Now

我可以通过以下流畅的查询获取最新查看的项目

return await _context.UserJobViews 
    .Where(x => x.UserId == thisUserId)
    .OrderByDescending(x => x.LastViewed)
    .Take(10)
    .Select(x => x.Job)
    .ProjectTo<JobDto>(_mapper.ConfigurationProvider)
    .ToListAsync();

然而,这显然不会为 JobDto 填充 LastViewedAt 属性。我该怎么做呢?

只需在配置中添加少量内容,即可实现:

CreateMap<UserJobView, JobDto>().IncludeMembers(s => s.Job);