自己写的AutoMapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
People p = new People() { Age = 28, name = new Name() { FirstName = "zheng", LastName = "zhiqiang" } };
PeopleDto pDto = new PeopleDto();
pDto = AutoMapping<People, PeopleDto>.Convert(p, pDto);
Console.WriteLine(string.Format("{0} {1} {2}", pDto.Age, pDto.FirstName, pDto.LastName));
Console.Read();
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1">entity</typeparam>
/// <typeparam name="T2">dto</typeparam>
public static class AutoMapping<T1, T2>
where T1 : new()
where T2 : new()
{
public static T2 Convert(T1 t1, T2 t2)
{
var dtoPiList = t2.GetType().GetProperties().Where(x => x.PropertyType.IsPublic).ToList();
string name;
object value;
for (int i = 0; i < dtoPiList.Count(); i++)
{
name = dtoPiList[i].Name;
value = GetPropertyValue(t1, name);
if (null == value) continue;
dtoPiList[i].SetValue(t2, value, null);
}
return t2;
}
private static object GetPropertyValue(object t1, string name)
{
Type t = t1.GetType();
PropertyInfo[] pis = t.GetProperties();
//查找当前对象是否包含需要转换的属性
var piTemp = pis.Where(x => x.Name == name).FirstOrDefault();
//不存在递归查询
if (piTemp == null)
{
foreach (PropertyInfo pi in pis)
{
object obj1 = pi.GetValue(t1, null);
object obj2 = GetPropertyValue(obj1, name);
if (obj2 != null) { return obj2; }
}
}
else
{
//判断是否忽略标记
var cAttr = piTemp.GetCustomAttributes();
foreach (var attr in cAttr)
{
var tempAttr = attr as AutoMappingAttributes;
if (tempAttr.Ignore) { return null; }
}
//存在直接返回
return piTemp.GetValue(t1, null);
}
return null;
}
}
public class AutoMappingAttributes : Attribute
{
public bool Ignore { get; set; }
}
public class Name
{
public string FirstName { get; set; }
[AutoMappingAttributes(Ignore = true)]
public string LastName { get; set; }
}
 
public class People
{
public int Age { get; set; }
public Name name { get; set; }
 
}
public class NameDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PeopleDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
 
}

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。