Using Entity Framework Core, I would like to get a list of the 10 most recently viewed jobs by a user.
I am working on a CRM which contains User
, Job
and UserJobView
classes.
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; }
}
I also have a JobDto
which I project to using 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; }
}
Each time a User
views a Job
I either update or create a UserJobView
object setting the LastViewedAt
property to be DateTime.Now
I can get the latest viewed items with the following fluent query
return await _context.UserJobViews
.Where(x => x.UserId == thisUserId)
.OrderByDescending(x => x.LastViewed)
.Take(10)
.Select(x => x.Job)
.ProjectTo<JobDto>(_mapper.ConfigurationProvider)
.ToListAsync();
However this obviously doesn't populate the LastViewedAt
property for the JobDto
. How might I go about doing this?
With a small addition to your configuration, you can make it happen:
CreateMap<UserJobView, JobDto>().IncludeMembers(s => s.Job);