【发布时间】:2020-07-01 02:12:13
【问题描述】:
我有一个 Post 和 Tag 类,在 PostTag 链接表中具有多对多关系。
public class Post
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<PostTag> PostTag { get; set; }
public string AppUserId { get; set; }
public AppUser AppUser { get; set; }
}
public class Tag
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<PostTag> PostTag { get; set; }
}
public class PostTag
{
public Guid PostId { get; set; }
public Post Post { get; set; }
public Guid TagId { get; set; }
public Tag Tag { get; set; }
}
我正在尝试使用 PostDto 的 AutoMapper 创建自定义映射,如下所示:
public class PostDto
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[JsonProperty("tags")]
public List<TagDto> PostTags { get; set; }
public UserDto User { get; set; }
}
public class TagDto
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class UserDto
{
public string DisplayName { get; set; }
}
这是我正在运行以返回所有帖子的查询:
var posts = await _ctx.Posts
.Include(s => s.PostTags)
.ThenInclude(st => st.Tag)
.ToListAsync();
return _mapper.Map<List<Post>, List<>>(posts); // _mapper is injected using IMapper
映射配置文件:
CreateMap<UserDto, AppUser>()
.ForMember(d => d.DisplayName, o => o.MapFrom(s => s.DisplayName));
CreateMap<Post, PostDto>();
.ForMember(d=> d.User, o=>o.MapFrom(s => s.Appuser))
.ForMember(d=> d.PostTags, o=>o.MapFrom(s=>s.PostTag));
CreateMap<PostTag, TagDto>()
.ForMember(d => d.Id, o => o.MapFrom(s => s.Tag.Id))
.ForMember(d => d.Name, o => o.MapFrom(s => s.Tag.Name));
导致此错误:
{
errors: "Error mapping types. Mapping types: List`1 -> List`1 System.Collections.Generic.List`1[[Domain.Post, Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List`1[[Application.PostDto, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"
}
【问题讨论】:
-
我们可以假设您在说 Mapster 时是指 AutoMapper 吗?
-
@NPras 是的。抱歉,我已经解决了。
标签: c# asp.net-core .net-core automapper