加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在代码外定义AutoMapper映射,即在XML文件中定义或使用

发布时间:2020-12-16 01:57:35 所属栏目:百科 来源:网络整理
导读:编辑:最初我打算使用AutoMapper来实现我的目标,但我必须知道AutoMapper并不打算以这种方式工作.它为您提供了创建配置文件的可能性,但在我的情况下(完全可配置)我需要为每个参数组合一个配置文件,所以我想出了一个自己的方法,看看答案. 从AutoMapper wiki我
编辑:最初我打算使用AutoMapper来实现我的目标,但我必须知道AutoMapper并不打算以这种方式工作.它为您提供了创建配置文件的可能性,但在我的情况下(完全可配置)我需要为每个参数组合一个配置文件,所以我想出了一个自己的方法,看看答案.

从AutoMapper wiki我学会了创建一个简单的映射

Mapper.CreateMap<CalendarEvent,CalendarEventForm>().ForMember(dest => dest.Title,opt => opt.MapFrom(src => src.Title));
    Mapper.CreateMap<CalendarEvent,CalendarEventForm>().ForMember(dest => dest.EventDate,opt => opt.MapFrom(src => src.EventDate.Date));
    Mapper.CreateMap<CalendarEvent,CalendarEventForm>().ForMember(dest => dest.EventHour,opt => opt.MapFrom(src => src.EventDate.Hour));
    Mapper.CreateMap<CalendarEvent,CalendarEventForm>().ForMember(dest => dest.EventMinute,opt => opt.MapFrom(src => src.EventDate.Minute));

像两个班

public class CalendarEvent
{
    public DateTime EventDate;
    public string Title;
}

public class CalendarEventForm
{
    public DateTime EventDate { get; set; }
    public int EventHour { get; set; }
    public int EventMinute { get; set; }
    public string Title { get; set; }
}

我现在想知道是否有可能在外部定义映射,例如在XML文件中

<ObjectMapping>
<mapping>
    <src>Title</src>
    <dest>Tile</dest>
</mapping>
<mapping>
    <src>EventDate.Date</src>
    <dest>EventDate</dest>
</mapping>
<mapping>
    <src>EventDate.Hour</src>
    <dest>EventHour</dest>
</mapping>
<mapping>
    <src>EventDate.Minute</src>
    <dest>EventMinute</dest>
</mapping>

并通过这种影响创建地图(XML不是一个要求,也可以是其他一切).
为简单起见,说类型没有问题,所以src和dest应该是相同的,否则可以失败.这背后的想法是在应该映射的内容和应该映射的位置上非常灵活.我正在考虑根据其名称获取属性值的反射,但这似乎不起作用.
我也不确定这是否有意义,或者我是否遗漏了重要的东西,所以我们非常感谢帮助和想法.

解决方法

最后,我实现了我自己的原始要求,尽管我不需要它(要求已更改).我会在这里提供代码以防有人需要它(或多或少作为概念证明,因为仍然可以进行大量改进)或者有兴趣,请记住,XML容易出错,在这种方法的关键组件,属性名称和类型必须完全匹配,否则它不会工作,但有一点GUI编辑文件这应该是可实现的(我的意思是不手动编辑文件).

我使用了here和here中的代码,并添加了类PropertyMapping来存储从XML读取的映射,还添加类Foo和Bar来创建嵌套数据结构,以便复制到.

无论如何这里是代码,也许它可以帮助某人一些时间:

主要:

public class Program
{
    public static void Main(string[] args)
    {
        // Model
        var calendarEvent = new CalendarEvent
        {
            EventDate = new DateTime(2008,12,15,20,30,0),Title = "Company Holiday Party"
        };

        MyObjectMapper mTut = new MyObjectMapper(@"SampleMappings.xml");

        Console.WriteLine(string.Format("Result MyMapper: {0}",Program.CompareObjects(calendarEvent,mTut.TestMyObjectMapperProjection(calendarEvent))));

        Console.ReadLine();
    }

    public static bool CompareObjects(CalendarEvent calendarEvent,CalendarEventForm form)
    {
        return calendarEvent.EventDate.Date.Equals(form.EventDate) &&
               calendarEvent.EventDate.Hour.Equals(form.EventHour) &&
               calendarEvent.EventDate.Minute.Equals(form.EventMinute) &&
               calendarEvent.Title.Equals(form.Title);
    }
}

Mapper实现:

public class MyObjectMapper
{
    private List<PropertyMapping> myMappings = new List<PropertyMapping>();

    public MyObjectMapper(string xmlFile)
    {
        this.myMappings = GenerateMappingObjectsFromXml(xmlFile);
    }

    /*
     * Actual mapping; iterate over internal mappings and copy each source value to destination value (types have to be the same)
     */ 
    public CalendarEventForm TestMyObjectMapperProjection(CalendarEvent calendarEvent)
    {
        CalendarEventForm calendarEventForm = new CalendarEventForm();

        foreach (PropertyMapping propertyMapping in myMappings)
        {
            object originalValue = GetPropValue(calendarEvent,propertyMapping.FromPropertyName);

            SetPropValue(propertyMapping.ToPropertyName,calendarEventForm,originalValue);
        }

        return calendarEventForm;
    }
    /*
     * Get the property value from the source object
     */ 
    private object GetPropValue(object obj,String compoundProperty)
    {
        foreach (String part in compoundProperty.Split('.'))
        {
            if (obj == null) { return null; }

            Type type = obj.GetType();
            PropertyInfo info = type.GetProperty(part);
            if (info == null) { return null; }

            obj = info.GetValue(obj,null);
        }
        return obj;
    }
    /*
     * Set property in the destination object,create new empty objects if needed in case of nested structure
     */ 
    public void SetPropValue(string compoundProperty,object target,object value)
    {
        string[] bits = compoundProperty.Split('.');
        for (int i = 0; i < bits.Length - 1; i++)
        {
            PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]);

            propertyToGet.SetValue(target,Activator.CreateInstance(propertyToGet.PropertyType));

            target = propertyToGet.GetValue(target,null);               
        }
        PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last());
        propertyToSet.SetValue(target,value,null);
    }              

    /*
     * Read XML file from the provided file path an create internal mapping objects
     */ 
    private List<PropertyMapping> GenerateMappingObjectsFromXml(string xmlFile)
    {
        XElement definedMappings = XElement.Load(xmlFile);
        List<PropertyMapping> mappings = new List<PropertyMapping>();

        foreach (XElement singleMappingElement in definedMappings.Elements("mapping"))
        {
            mappings.Add(new PropertyMapping(singleMappingElement.Element("src").Value,singleMappingElement.Element("dest").Value));
        }

        return mappings;
    } 
}

我的模型类:

public class CalendarEvent
{
    public DateTime EventDate { get; set; }
    public string Title { get; set; }
}

public class CalendarEventForm
{
    public DateTime EventDate { get; set; }
    public int EventHour { get; set; }
    public int EventMinute { get; set; }
    public string Title { get; set; }
    public Foo Foo { get; set; }
}

public class Foo
{
    public Bar Bar { get; set; }

}

public class Bar
{
    public DateTime InternalDate { get; set; }

}

内部映射表示:

public class PropertyMapping
{
    public string FromPropertyName;
    public string ToPropertyName;

    public PropertyMapping(string fromPropertyName,string toPropertyName)
    {
        this.FromPropertyName = fromPropertyName;
        this.ToPropertyName = toPropertyName;
    }
}

示例XML配置:

<?xml version="1.0" encoding="utf-8" ?>
    <ObjectMapping>
      <mapping>
        <src>Title</src>
        <dest>Title</dest>
       </mapping>
      <mapping>
        <src>EventDate.Date</src>
        <dest>EventDate</dest>
      </mapping>
      <mapping>
        <src>EventDate.Hour</src>
        <dest>EventHour</dest>
      </mapping>
      <mapping>
        <src>EventDate.Minute</src>
        <dest>EventMinute</dest>
      </mapping>
      <mapping>
        <src>EventDate</src>
        <dest>Foo.Bar.InternalDate</dest>
      </mapping>
     </ObjectMapping>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读