-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoMapper.cs
More file actions
74 lines (61 loc) · 2.16 KB
/
AutoMapper.cs
File metadata and controls
74 lines (61 loc) · 2.16 KB
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
using System;
using System.Reflection;
namespace AutoMapper
{
public class AutoMapper
{
public static TTarget Map<TSource, TTarget>(TSource source)
where TTarget : new()
{
if (source == null) return default!;
TTarget target = new TTarget();
var sourceProps = typeof(TSource).GetProperties();
var targetProps = typeof(TTarget).GetProperties();
foreach (var tProp in targetProps)
{
if (!tProp.CanWrite) continue;
// Case-insensitive match
var sProp = sourceProps.FirstOrDefault(
sp => string.Equals(sp.Name, tProp.Name, StringComparison.OrdinalIgnoreCase)
);
if (sProp == null) continue;
var sValue = sProp.GetValue(source);
if (sValue == null)
{
// If nullable → non-nullable, assign default value ("" for string)
if (!IsNullable(tProp.PropertyType))
{
tProp.SetValue(target, GetDefaultValue(tProp.PropertyType));
}
continue;
}
// Type matches → direct assign
if (tProp.PropertyType == sProp.PropertyType)
{
tProp.SetValue(target, sValue);
continue;
}
// Try convert types (string ↔ int, etc.)
try
{
var converted = Convert.ChangeType(sValue, tProp.PropertyType);
tProp.SetValue(target, converted);
}
catch
{
// ignore conversion errors
}
}
return target;
}
private static bool IsNullable(Type t)
{
return !t.IsValueType || Nullable.GetUnderlyingType(t) != null;
}
private static object GetDefaultValue(Type t)
{
if (t == typeof(string)) return string.Empty;
return Activator.CreateInstance(t)!;
}
}
}