【问题标题】:Projecting included objects投影包含的对象
【发布时间】:2020-05-28 18:27:03
【问题描述】:

我正在寻找一种方法来在 EntityFramework Core 中以我们可以投影对象的方式投影包含的对象(选择函数):

[HttpGet]
    public async Task<IActionResult> GetBooks()
    {
        return Json(new { data = await _db.Books.Select(b => _mapper.Map<BookDto>(b)).ToListAsync() });
    }

这是我尝试投影包含的对象但它无效的代码:

[HttpGet]
    public async Task<JsonResult> GetMessagesAsync()
    {
        var msgs = await _db.Messages.OrderBy(m => m.Sent).Include(m => _mapper.Map<AppUserDto>(m.AppUser)).ToListAsync();
        return Json(new { data = msgs });
    }

编辑1: 我想将包含的 AppUser 对象投影到 AppUserDto 中。

EDIT2:

public MappingProfile()
    {
        CreateMap<Book, BookDto>();
        CreateMap<BookDto, Book>();

        CreateMap<Client, ClientDto>();
        CreateMap<ClientDto, Client>();

        CreateMap<Reservation, ReservationDto>();
        CreateMap<ReservationDto, Reservation>();

        CreateMap<AppUser, AppUserDto>();
        CreateMap<AppUserDto, AppUser>();
    }

【问题讨论】:

标签: c# .net .net-core entity-framework-core automapper


【解决方案1】:

如果您的映射器设置正确,您应该能够执行以下操作:

var msgs = await _db.Messages
     .OrderBy(m => m.Sent)
     .Include(m => m.AppUser)
     .Select(m => _mapper.Map<MessageDto>(m))
     .ToListAsync();

因此,您的 MessageDto 将需要具有 AppUserDto AppUser 属性等。

【讨论】:

  • 这里是我想要投影包含的 AppUser 类的对象 -> AppUserDto
  • 你在使用自动映射器吗?
  • 是的,我创建了 MappingProfile "CreateMap();"
  • 你有一些`CreateMap 映射吗?如果是,请为这两个类添加代码。
  • 提议的代码会将Message对象投影到MessageDto中
猜你喜欢
  • 2015-10-15
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多