处理同一源对象和目标对象的多个映射

问题描述 投票:0回答:1

我有Source类和Destination类要映射。目标类是诸如Person之类的通用类,它将用作我的某个类(MainClass)中各个字段(例如父亲,母亲,兄弟等)中的一个字段。我如何将来自父亲的数据从源映射到目标,母亲等

我可以创建

CreateMap<Source, MainClass>()
.ForMember(dest => dest.Mother, m => m.MapFrom(source => source))
.ForMember(dest => dest.Father, m => m.MapFrom(source => source))
.ForMember(dest => dest.Brother, m => m.MapFrom(source => source));

 Mapper.CreateMap<Source, Destination>()  
.ForMember(dest => dest.Name,  m => m.MapFrom(source => source.motherName))
.ForMember(dest => dest.ID,  m => m.MapFrom(source => source.motherId))
.ForMember(dest => dest.Address,  m => m.MapFrom(source => source.motherAddress));

但是我如何处理父亲,兄弟等的映射以实现

 Mapper.CreateMap<Source, Destination>()  
.ForMember(dest => dest.Name,  m => m.MapFrom(source => source.FatherName))
.ForMember(dest => dest.ID,  m => m.MapFrom(source => source.FatherId))
.ForMember(dest => dest.Address,  m => m.MapFrom(source => source.FatherAddress));
c# .net automapper
1个回答
0
投票

确定,这是来自记事本编辑器的未经测试的代码:D

您可以尝试一下,并根据需要进行更改。从一开始这是行不通的!

opt.MapFrom(源=> SetName(源,“母亲”)))

    private object SetName(Person y, string personState)
    {
        Person person = new Person();
        var properties = DictionaryFromType(y);
        foreach(var property in properties)
        {
            if(property.Key.ToLower().Contains(personState.ToLower()))
            {
     // you should make the real mapping to id here. This is just example code on how it could work
                PropertyInfo propertyInfo = person.GetType().GetProperty(property.Key);
                propertyInfo.SetValue(person, Convert.ChangeType(property.Value, propertyInfo.PropertyType), null);
            }
        }

        return person;
    }

    public static Dictionary<string, object> DictionaryFromType(object atype)
    {
        if (atype == null) return new Dictionary<string, object>();
        Type t = atype.GetType();
        PropertyInfo[] props = t.GetProperties();
        Dictionary<string, object> dict = new Dictionary<string, object>();
        foreach (PropertyInfo prp in props)
        {
            object value = prp.GetValue(atype, new object[] { });
            dict.Add(prp.Name, value);
        }
        return dict;
    }

也许您需要调试一下才能使其正常运行,但是可以通过某种方式使它运行。

自动映射器可能有更好的解决方案,但目前我只想到这一点。

希望这可以帮助您,即使这还没有完成! (对不起,我的时间太少了)

© www.soinside.com 2019 - 2024. All rights reserved.