【问题标题】:Conditional Automapper Doesn't Work For MapFrom条件自动映射器不适用于 MapFrom
【发布时间】: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


    【解决方案1】:

    Uppps,我忘记了虚拟关键字。现在一切正常。

    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 virtual ApplicationUser User { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 2014-11-08
      • 2017-07-05
      • 2012-09-28
      • 2018-02-18
      相关资源
      最近更新 更多