【发布时间】:2021-04-18 12:37:48
【问题描述】:
我在两种情况下使用条件映射,其中一种有效,另一种无效。 我的实体在这里
public class Form
{
public int FormId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int? UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
}
我的映射配置代码在这里,如果“UserId”不同于null,则应该从关系中获取,否则从表中获取。
cfg.CreateMap<Form, FormDto>()
.ForMember(d => d.Name, opt => opt.MapFrom(c => c.UserId != null ? c.User.Name : c.Name));
而且这段代码有效,没有问题。
var forms = _unitOfWork.FormRepository
.GetConversations(mainFormId)
.ProjectTo<FormDto>(_mapper.ConfigurationProvider)
.ToList();
//it gets "Name" fine from relation mapping
Console.Write(forms[0].Name)
但是这段代码不起作用,问题就在这里。
var formDto = _mapper.Map<FormDto>(_unitOfWork.FormRepository.GetForm(mainFormId));
//The "Name" property is empty but it should be get it from relation
Console.Write(formDto.Name)
请问你有什么建议?
谢谢
【问题讨论】:
标签: c# asp.net .net asp.net-mvc automapper