gpt4 book ai didi

c# - AutoMapper .ForMember 用于收集

转载 作者:行者123 更新时间:2023-11-30 16:02:52 29 4
gpt4 key购买 nike

我有实体 Request 和模型 RequestModel

public class RequestModel : BaseModel
{
public IEnumerable <int> Recipients { get; set; }
}

public class Request : IIdent
{
public virtual ICollection <RequestComment> Comments { get; set; }
}

public class RequestComment : IIdent
{
[ForeignKey("User")]
public int? UserId { get; set; }
}

我想为 Recipients 创建映射

CreateMap<Request, RequestModel>()
.ForMember(d => d.Recipients, o => o.MapFrom(s => s.Comments.Select(x => x.UserId )))

但是我遇到了异常:

AutoMapper.AutoMapperMappingException was caught _HResult=-2146233088 HResult=-2146233088 IsTransient=false Message= Mapping types: Request -> IEnumerable1
AttManager.Data.Request -> System.Collections.Generic.IEnumerable
1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Destination path: RequestModel.Recipients.Recipients Source value: AttManager.Data.Request

最佳答案

当您尝试转换 IEnumerable<RequestComment> 时,问题就来了至 IEnumerable<int> ,所以 Automapper 将尝试找到 RequestComment 之间的转换至 int , 但未定义。

您可以定义从 RequestComment 的转换至 int像这样:

.CreateMap<RequestComment, int>().ConvertUsing(rm => rm.UserId ?? 0);

以及请求模型之间的映射:

.CreateMap<Request, RequestModel>()
.ForMember(d => d.Recipients, o => o.MapFrom(s => s.Comments))

此外,另一种解决问题的方法是定义一个 AfterMap操作:

.CreateMap<Request, RequestModel>()
.AfterMap((r, rm) => rm.Recipients = new List<int>(r.Comments.Select(c => c.UserId ?? 0)));

我只是添加?? 0因为UserId类型是 int? , 所以需要转换为 int对于 Recipients属性(property)。

关于c# - AutoMapper .ForMember 用于收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37144513/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com