问题描述
使用 Entity Framework Core,我想获取用户最近查看的 10 个作业的列表。
我正在开发一个包含 User
、Job
和 UserJobView
类的 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();
然而,这显然不会填充 LastViewedAt
的 JobDto
属性。我该怎么做?
解决方法
只需对您的配置进行少量添加,您就可以实现:
CreateMap<UserJobView,JobDto>().IncludeMembers(s => s.Job);