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

问题描述

使用 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();

然而,这显然不会填充 LastViewedAtJobDto 属性。我该怎么做?

解决方法

只需对您的配置进行少量添加,您就可以实现:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...