Adapt navigational property using Mapster

Viewed 3766

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

1 Answers

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>();
Related