使用 Mapster 调整导航 属性
Adapt navigational property using Mapster
我有一个 Post
class,里面有一个 User
属性。当我尝试获取所有帖子时,我还想将 User
映射到 UserDto
对象。
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()
在 Include
内部进行适配会引发此错误:
Lambda expression used inside Include is not valid
您似乎混淆了 Include
,因为 Entity Framework
和 Mapster
都具有该功能。您向我们展示的 Include
属于 Entity Framework
: https://docs.microsoft.com/en-us/ef/core/querying/related-data#eager-loading
因此,首先您需要使用 Include
检索数据,如下所示:
var result = await _ctx.Posts.Include(u => u.User).ToListAsync();
另一方面,您需要设置 mapster 配置:
TypeAdapterConfig<Post, PostDto>.NewConfig()
.PreserveReference(true);
TypeAdapterConfig<User, UserDto>.NewConfig()
.PreserveReference(true);
请参阅 Mapster 中的嵌套映射:
https://github.com/MapsterMapper/Mapster/wiki/Config-for-nested-mapping
因此你可以得到 PostDto
其中包括 UserDto
:
var postDto = result.Adapt<PostDto>();
我有一个 Post
class,里面有一个 User
属性。当我尝试获取所有帖子时,我还想将 User
映射到 UserDto
对象。
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()
在 Include
内部进行适配会引发此错误:
Lambda expression used inside Include is not valid
您似乎混淆了 Include
,因为 Entity Framework
和 Mapster
都具有该功能。您向我们展示的 Include
属于 Entity Framework
: https://docs.microsoft.com/en-us/ef/core/querying/related-data#eager-loading
因此,首先您需要使用 Include
检索数据,如下所示:
var result = await _ctx.Posts.Include(u => u.User).ToListAsync();
另一方面,您需要设置 mapster 配置:
TypeAdapterConfig<Post, PostDto>.NewConfig()
.PreserveReference(true);
TypeAdapterConfig<User, UserDto>.NewConfig()
.PreserveReference(true);
请参阅 Mapster 中的嵌套映射:
https://github.com/MapsterMapper/Mapster/wiki/Config-for-nested-mapping
因此你可以得到 PostDto
其中包括 UserDto
:
var postDto = result.Adapt<PostDto>();