Auto Mapper02《demo》

     学习这些基本上网上都有一些教程或者别人做的demo,我是按照这个方式去学习的。先做个demo,学会如何去使用它,接着去慢慢的了解它是如何的运行的,理解里面的一些基本的基础知识。我们不可以再像学校里面的那样,先去学习基本的结构,那样我们会很烦脑的,我们应该先学会使用它,接着再去慢慢的了解。

  “高内聚低耦合,尽量依赖抽象而不依赖于具体”,这个在面向对象的开发中是很常见的,autoMapper就可以很好的解释这个。automapper具体的功能就是将数据库中的实体表转换为我们页面上使用的model,虽然我们可以直接使用实体的Model,但是我们为了以后着想,界面上使用我们自己定义的Modell,只需要我们利用automapper进行转换就可以了。因为我们的实体Model是最容易发生变化的。

image

    下面是我安装网上的教程做的demo。

书类

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
//书店
  public class BookStore
  {
      public string Name { get; set; }
      public List<Book> Books { get; set; }
      public Address Address { get; set; }
  }
  //书店的地址
  public class Address
  {
      public string Country { get; set; }
      public string City { get; set; }
      public string Street { get; set; }
      public string PostCode { get; set; }
  }
  // 书类
  public class Book
  {
      public string Title { get; set; }
      public string Description { get; set; }
      public string Lauguage { get; set; }
      public decimal Price { get; set; }
      public DateTime? PublishDate { get; set; }
      public Publisher Publisher { get; set; }
      public int? Paperback { get; set; }
      public List<Author> Authors { get;set; }
  }
  //出版信息
  public class Publisher
  {
      public string Name { get; set; }
  }
  //每本书都有2个作者
  public class Author
  {
      public string Name { get; set; }
      public string Description { get; set; }
      public ContactInfo ContactInfo { get; set; }
  }
  //联系法式
  public class ContactInfo
  {
      public string Email { get; set; }
      public string Blog { get; set; }
      public string Twitter { get; set; }
  }

书Dto

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
//书店
public class BookStoreDto
{
    public string Name { get; set; }
    public List<BookDto> Books { get; set; }
    public AddressDto Address { get; set; }
}
//书店地址
public class AddressDto
{
    public string Country { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
    public string PostCode { get; set; }
}
//这个是对应的Book类
public class BookDto
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Language { get; set; }
    public decimal Price { get; set; } 
    public DateTime? PublishDate { get; set; } 
    public string Publisher { get; set; } 
    public int? Paperback { get; set; } 
    //01作者信息
    public string FirstAuthorName { get; set; } 
    public string FirstAuthorDescription { get; set; } 
    public string FirstAuthorEmail { get; set; } 
    public string FirstAuthorBlog { get; set; } 
    public string FirstAuthorTwitter { get; set; } 
    //02作者信息
    public string SecondAuthorName { get; set; } 
    public string SecondAuthorDescription { get; set; } 
    public string SecondAuthorEmail { get; set; } 
    public string SecondAuthorBlog { get; set; } 
   public string SecondAuthorTwitter { get; set; } 
}

我们可以发现dto里面将book的整个层级结构 ,全面拉平了,就是说放到了一个类里面,其实我们强大的AutoMapper是可以自动的进行映射的,还有我们的名字不一样的,但是只要是后面的是一样的是可以映射的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Mapper.CreateMap<AddressDto, Address>();
AddressDto dto=new AddressDto()
{
    Country = "China",
    City = "XiAn",
    Street = "YUlin",
    PostCode = "001"
};
//配置二者的转换
Mapper.CreateMap<AddressDto, Address>();
//这个映射的时候是从左向右的
Address address = Mapper.Map<AddressDto,Address>(dto);
Console.WriteLine(address.Country);
Console.WriteLine(address.PostCode);
Console.ReadKey();

规则:

  1:若是一个里面有空属性,那么利用AutoMapper映射过去相应的属性就会为空。

  2:可以进行手工的传递。直接就是DTO中的一个属性可以直接映射到Modle中的一个类,但是需要我们自己进行设置。AutoMapper利用ForMember来指定每一个字段的映射规则的。

1
Mapper.CreateMap<Blog, Model>().ForMember(x => x.BlogCon, mo => mo.MapFrom(x => x.BlogContext));

bookDto的转换

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
//集合初始化器
BookStoreDto dto=new BookStoreDto()
{
    Name = "ahui",
    Address = new AddressDto
    {
        City = "YUlin"
    },
    Books = new List<BookDto>
    {
        new BookDto
        {
            Title = "你好世界"
        },
        new BookDto
        {
            Title = "世界你好"
        }
    }
};
//配置,这里要将转换的内容全部进行配置
Mapper.CreateMap<BookStoreDto, BookStore>();
Mapper.CreateMap<AddressDto, Address>();
Mapper.CreateMap<BookDto, Book>();
//IMappingExpression<BookDto, Book> expression = Mapper.CreateMap<BookDto, Book>();
//转换
BookStore bookStore = Mapper.Map<BookStoreDto,BookStore>(dto);           
//利用bookStore输出
Console.WriteLine(bookStore.Address.Country);
Console.WriteLine(bookStore.Name);
foreach (var item in bookStore.Books)
{
    Console.WriteLine(item.Title);               
}
Console.ReadKey();

image

这样就成功了。

3:autoMapper中的ConstructUsing。

  我们想一次性的定义好所有的字段,我们就可以使用ConstructUsing来操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//配置  这里还是说将名称不同的变量之间进行映射。
         //定义BookDto到第一作者(Author)的ContactInfo之间的映射。
         var map = Mapper.CreateMap<BookDto,ContactInfo>();
         map.ConstructUsing(s=>new ContactInfo
         {
             Blog = s.FirstAuthorBlog,
             Email = s.FirstAuthorEmail,
             Twitter=s.FirstAuthorTwitter
         });
         //转换
         BookDto dto=new BookDto()
         {               
             FirstAuthorEmail = "1193451014@qq.com",
             FirstAuthorBlog="www.cnblogs.com/netxiaohui",                 
         };
         ContactInfo contactInfo = Mapper.Map<ContactInfo>(dto);
         Console.WriteLine(contactInfo.Blog);
         Console.WriteLine(contactInfo.Email);
         Console.ReadKey();

image

4:验证配置是否有效,无效的话会抛出异常的,。

1
Mapper.AssertConfigurationIsValid();

这里的抛出异常(AutoMapperConfigurationException),我们别小看它,在他执行期间,AutoMapper会检查每个目标类型的属性,一对一的去匹配源中是否存在合适相等的类型。

5:使用忽略选项(Ignore())

情景:目标类型有个成员,不能完成转换,我们不想让其转换,可以这样配置。

1
2
//我们不想再转换的时候将Book的Title进行转换,可以将其忽略
Mapper.CreateMap<BookDto, Book>().ForMember(dest=>dest.Title,opt=>opt.Ignore());

错误:出现了和上次一样的错误。

“{"Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nBookStoreDto -> BookStore\r\nAMapper.Class.BookStoreDto -> AMapper.Class.BookStore\r\n\r\nDestination path:\r\nBookStore\r\n\r\nSource value:\r\nAMapper.Class.BookStoreDto"}”

这个就是没有进行配置,就是说AutoMapper不知道你要如何去转换,后来才发现我写反了,应该先进行配置在转换。

image

就是错在了这里。

附件

  “呆河马”     http://www.cnblogs.com/jobs2/p/3503990.html

  “魔古先生”  http://www.cnblogs.com/mushroom/p/4291975.html

posted @   —阿辉  阅读(687)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示