【问题标题】:Entity Framework Core Automapper latest viewed items for a specific userEntity Framework Core Automapper 特定用户的最新查看项目
【发布时间】:2021-05-13 09:04:51
【问题描述】:

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

但是,这显然不会填充JobDtoLastViewedAt 属性。我该怎么做呢?

【问题讨论】:

  • CreateMap&lt;UserJobView, JobDto&gt;().IncludeMembers(s =&gt; s.Job).
  • @LucianBargaoanu 如果您将其作为官方答案,我会接受,因为这正是我想要的,谢谢!

标签: entity-framework-core automapper fluent


【解决方案1】:

只需对您的配置进行一点补充,您就可以实现它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多