用nuget安装AutoMapper。
如果熟悉相同,可以直接mapper;如果不同,就需要定义下mapper规则,这里先展示个简单的用法。
一些类:
public class Book
{
public string Title { get; set; }
public Author Author { get; set; }
public Prd product { get; set; }
}
public class BookViewModel
{
public string Title { get; set; }
public string Author { get; set; }
public string ItemNo { get; set; }
}
public class Author
{
public string Name { get; set; }
}
public class Prd
{
public string itemNo { get; set; }
public string model { get; set; }
}
使用:
static void Main(string[] args)
{
//方式1:
var a = new AutoMapper.Configuration.MapperConfigurationExpression();
a.CreateMap<Book, Author>().ForMember(dest => dest.Name,
opts => opts.MapFrom(src => src.Author.Name));
a.CreateMap<Book, BookViewModel>().ForMember(dest => dest.ItemNo,
opts => opts.MapFrom(src => src.product.itemNo))
.ForMember(dest => dest.Author,
opts => opts.MapFrom(src => src.Author.Name));
AutoMapper.Mapper.Initialize(a);
//方式2:
//AutoMapper.Mapper.Initialize(c => {
// c.CreateMap<Book, BookViewModel>().ForMember(dest => dest.Author,
// opts => opts.MapFrom(src => src.Author.Name));
// c.CreateMap<Book, Author>().ForMember(dest => dest.Name,
// opts => opts.MapFrom(src => src.Author.Name));
//});
Book b1 = new Book();
b1.Title = "题目";
b1.Author = new Author();
b1.Author.Name = "作者";
b1.product = new Prd();
b1.product.itemNo = "12001";
b1.product.model = "a3001";
BookViewModel bvm = AutoMapper.Mapper.Map<BookViewModel>(b1);
Console.WriteLine(JsonHelper.ToJson(bvm));
Author author = AutoMapper.Mapper.Map<Author>(b1);
Console.WriteLine(JsonHelper.ToJson(author));
Console.ReadKey();
}
结果:
image.png
网友评论