AutoMapper IMemberValueResolver源对象到成员属性映射问题

时间:2017-11-29 16:31:05

标签: c# automapper

我有一个嵌套的Entity Framework对象,其中包含下拉列表中使用的显示标题的翻译。我试图从整个源对象中解析显示标题,但我无法弄清楚正确的语法。

这是解析器:

public class IssueTypeResolver : IMemberValueResolver<lstIssueType, string, string, string>
{
    public string Resolve(lstIssueType source, string destination, string sourceMember, string destMember, ResolutionContext context)
    {
        // culture override from resources if available
        var cultureCode = context.Options.Items["CultureCode"].ToString();
        if (source.refResourceType != null && source.refResourceType.Resources != null)
        {
            var cultureOverride = source.refResourceType.Resources.FirstOrDefault(r => r.CultureCode == cultureCode);
            if (cultureOverride != null)
            {
                return cultureOverride.ResourceText;
            }
        }

        return source.DisplayTitle;
    }
}

这是配置图:

cfg.CreateMap<DataAccess.DbModel.lstIssueType, Contract.IssueType>()
    .ForMember(
        d => d.Description, 
        opts => opts.ResolveUsing<IssueType2Resolver, string>(????));

我需要将整个lstIssueType作为源传递,但我无法弄清楚如何这样做。

1 个答案:

答案 0 :(得分:1)

如果有人感兴趣的解决方案如下,并使用IValueResolver而不是IMemberValueResolver

public class IssueTypeResolver : IValueResolver<lstIssueType, IssueType, string>
{
    public string Resolve(lstIssueType source, IssueType destination, string member, ResolutionContext context)
    {
        var cultureCode = context.Options.Items["CultureCode"].ToString();
        if (source.refResourceType != null && source.refResourceType.Resources != null)
        {
            var cultureOverride = source.refResourceType.Resources.FirstOrDefault(r => r.CultureCode == cultureCode);
            if (cultureOverride != null)
            {
                return cultureOverride.ResourceText;
            }
        }

        return source.DisplayTitle;
    }
}

匹配的配置图:

cfg.CreateMap<lstIssueType, IssueType>()
    .ForMember(d => d.Description, opts => opts
        .ResolveUsing<IssueTypeResolver>(src => src.refResourceType));