-
Notifications
You must be signed in to change notification settings - Fork 1
/
ObjectMapper.cs
58 lines (47 loc) · 1.57 KB
/
ObjectMapper.cs
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
using System.Dynamic;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Query.Internal;
namespace SqlToObjectify
{
public static class ObjectMapper
{
public static T? MapToObject<T>(this object? result)
{
if (result is not ExpandoObject obj)
{
return default(T);
}
//var model = new T();
var model = Activator.CreateInstance<T>();
var type = typeof(T);
SetProperties(obj, type, model);
return model;
}
public static List<T>? MapToObjectList<T>(this object? result)
{
if (result is not List<ExpandoObject> listObjList)
{
return default;
}
var modelList = new List<T>();
var type = typeof(T);
foreach (var listObj in listObjList)
{
var listItem = Activator.CreateInstance<T>();
SetProperties(listObj, type, listItem);
modelList.Add(listItem);
}
return modelList;
}
private static void SetProperties<T>(ExpandoObject obj, IReflect type, T model)
{
foreach (var (key, value) in obj)
{
var property = type.GetProperty(key,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (property == null) continue;
property.SetValue(model, Convert.ChangeType(value, property.PropertyType));
}
}
}
}