0%

AutoMapper運用 (二)

如果是複雜Class要Mapper時

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Category 
{
public int id { get; set; }
public List<product> products {get;set;}
}

public class Product
{
public int id { get; set; }
public string name { get; set; }
public int qantity {get;set;}
}

Category要Mapping到CategoryViewModel

1
2
3
4
5
6
7
8
9
10
11
12
13
public class CategoryViewModel 
{
public int id { get; set; }
public List<Book> books {get;set;}
}

public class Book
{
public string title {get;set;}

public int number{get;set;}
}

有兩種做法,結果都會是一樣的

  1. ```csharp
    Category category = new Category()
    {
    id = 1,
    products = new List()
    {
    new Product()
    {
    id = 1,
    name = “西遊戲”,
    qantity =10,
    },
    new Product()
    {
    id = 2,
    name = “三國志”,
    qantity =30,
    },
    new Product()
    {
    id = 3,
    name = “鹿鼎記”,
    qantity =50,
    }
    }
    };

    Mapper.CreateMap<Category, CategoryViewModel>()
    .ForMember(d => d.id, o => o.MapFrom(s => s.id))
    .ForMember(d => d.books, o => o.MapFrom(s => s.products));

    Mapper.CreateMap<Product, Book>()
    .ForMember(d => d.title, o => o.MapFrom(s => s.name))
    .ForMember(d => d.number, o => o.MapFrom(s => s.qantity));

var viewModel = Mapper.Map(category);
viewModel.Dump();

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

2. ```csharp
void Main()
{
Category category = new Category()
{
id = 1,
products = new List<Product>()
{
new Product()
{
id = 1,
name = "西遊戲",
qantity =10,
},
new Product()
{
id = 2,
name = "三國志",
qantity =30,
},
new Product()
{
id = 3,
name = "鹿鼎記",
qantity =50,
}
}
};

Mapper.CreateMap<Category, CategoryViewModel>()
.ForMember(d => d.id, o => o.MapFrom(s => s.id))
.ForMember(d => d.books, o => o.ResolveUsing<BookResolve>().FromMember(s => s.products));

var viewModel = Mapper.Map<CategoryViewModel>(category);
viewModel.Dump();
}

public class BookResolve : ValueResolver<IList<Product>, IList<Book>>{
protected override IList<Book> ResolveCore(IList<Product> source) {
List<Book> books = new List<Book>();
foreach (var item in source)
{
var book = new Book() {
number = item.qantity,
title = item.name
};
books.Add(book);
}
return books;
}
}