1

I have a Post class with a User property in it. When I try to get all Posts, I also want to map the User to a UserDto object.

public class Post {
    public Guid Id {get; set;}
    public string Content {get;set;}
    public User User {get; set;}
}


var result = await _ctx.Posts.Include(u => u.User.Adapt<UserDto>()).ToListAsync()

Adapting inside the Include is throwing this error:

Lambda expression used inside Include is not valid

Selim Yildiz
  • 4,978
  • 6
  • 16
  • 25
blankface
  • 4,595
  • 13
  • 57
  • 97

1 Answers1

2

It seems you are mixing up Include because Entity Framework and Mapster both have that function. The Include that you showed us belongs to Entity Framework : https://docs.microsoft.com/en-us/ef/core/querying/related-data#eager-loading

So, first you need to retrieve data with using Include as follows:

var result = await _ctx.Posts.Include(u => u.User).ToListAsync();

On the other hand you need to set mapster config:

TypeAdapterConfig<Post, PostDto>.NewConfig()
    .PreserveReference(true);

TypeAdapterConfig<User, UserDto>.NewConfig()
    .PreserveReference(true);

See for nested mapping in Mapster:

https://github.com/MapsterMapper/Mapster/wiki/Config-for-nested-mapping

Thus you can get PostDto which includes UserDto:

var postDto = result.Adapt<PostDto>();
Selim Yildiz
  • 4,978
  • 6
  • 16
  • 25
  • Seems to work fine without the mapster config, as long as the Dto property name matches the source object name. Is this expected? – blankface Jun 10 '20 at 06:28