2、Automapper安装及配置

database

一、 安装

我们安装是在 vs 中使用Nuget的方式进行安装

不过安装时需注意一件事情就是,版本问题,我示例使用的是.net framework 4.5.2,所以我安装AutoMapper的版本是7.0,如果安装失败,把版本降低一下就可以。

 

二、配置

staticvoid Main(string[] args)

{

//配置,写的位置随意,因为是全局的

Mapper.Initialize(m => m.CreateMap<Person, People>());

//对象

Person person = new Person()

{

Name = "text1",

Age = 12,

Birthday = DateTime.Now,

Sex = true,

Salary = 1000

};

People peo = new People(); //不能位Null

//转换

Mapper.Map(person, peo);

//显示

Console.WriteLine(peo.Name);

Console.WriteLine(peo.Age);

Console.WriteLine(peo.Birthday);

Console.Read();

 

此外还有一种方式就是不需要New 实例化:

 People peo = new People(); //不能位Null

我们可以直接转化,但是,需要使用泛型指定转换类型

  People peo2 = Mapper.Map<People>(person);

三、 AutoMapper 配置多个

//配置

Mapper.Initialize(m =>

{

m.CreateMap<Person, People>();

m.CreateMap<ABP, People>();

});

以上是 2、Automapper安装及配置 的全部内容, 来源链接: utcz.com/z/531913.html

回到顶部