C#实现对象映射AutoMapper

reference website :https://www.cnblogs.com/besos/p/13384764.html

1.引用AutoMapper包

2.定义两个实体类

1
2
3
4
5
6
7
8
9
10
11
12
public class ModelA
       {
           public string UserId { getset; }
           public string Remark { getset; }
       }
 
      public class ModelB
       {
           public string User_id { getset; }
           public string Remark_msg { getset; }
           public int Lab_id { getset; }
       }

3.定义映射规则,并映射

1
2
3
4
5
6
7
8
9
10
11
12
public List<ModelB> MappingModeB(List<ModelA> data, int lab_Id)
       {
           MapperConfiguration config = new MapperConfiguration
          (
              mp => mp.CreateMap<ModelA, ModelB>()  //  给config进行配置映射规则
                      .ForMember(nclog => nclog.User_id, clog => clog.MapFrom(log => log.UserId == null "" : log.UserId))  // 指定映射字段
                      .ForMember(nclog => nclog.Remark_msg, clog => clog.MapFrom(log => log.Remark))
                      .ForMember(nclog => nclog.Lab_id, clog => clog.MapFrom(log => lab_Id))
          );
           var Modellogs = config.CreateMapper();
           return Modellogs.Map<List<ModelB>>(data);  //映射
       }

C#实现对象映射

ref:https://blog.csdn.net/u010655942/article/details/49535723

有时候会遇到这样的问题,两个对象具有很多相同的属性,已知一个对象,要给另外一个对象赋值,这时候需要每个属性逐一赋值,会比较麻烦。

如果不考虑性能问题的话,可以使用对象映射的方式来赋值,实际上是利用了反射的机制,达到动态生成对象和动态类型转换的目的。

实现代码如下:

using System;
using Newtonsoft.Json;

namespace ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
string s = string.Empty;
var person = new Person { Name = "张三", Age = "12", Birthday = "2015/10/31 19:56:30" };
var student = EntityMapper<Student, Person>(person);
s = JsonConvert.SerializeObject(student);
Console.WriteLine(s);
Console.ReadKey();
}

static TTo EntityMapper<TTo, TFrom>(TFrom from)
{
var to = Activator.CreateInstance<TTo>();
var tTo = typeof(TTo);
var psFrom = typeof(TFrom).GetProperties();
foreach (var pFrom in psFrom)
{
var vFrom = pFrom.GetValue(from);
if (vFrom != null)
{
var pTo = tTo.GetProperty(pFrom.Name);
if (pTo != null)
{
var pToType = pTo.PropertyType;
if (pToType.IsGenericType && pToType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var vTo = Convert.ChangeType(vFrom, pToType.GetGenericArguments()[0]);
pTo.SetValue(to, vTo);
}
else
{
var vTo = Convert.ChangeType(vFrom, pTo.PropertyType);
pTo.SetValue(to, vTo);
}
}
}


}
return to;
}

public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public string Birthday { get; set; }
}

public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
}
}
注意,这段代码没有经过严格测试,请谨慎使用。
如果真实项目需要对象映射的功能,推荐使用AutoMapper
————————————————
版权声明:本文为CSDN博主「717606641」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010655942/article/details/49535723

原文地址:https://www.cnblogs.com/bruce1992/p/15342481.html