C# AutoMapper 使用簡易說明


AutoMapper 是 C# 中常用的第三方映射庫,比如有下面兩個類

    public class 學生 { public string 姓名 { get; set; } public int 年齡 { get; set; } } public class Student { public string Name { get; set; } public int Age { get; set; } }

假如,外部傳進來(如走WebApi)的類是 Student ,而我們的軟件的實體類是“學生”類,那么我想把 Student 轉成 學生 類,則一般我們采用的方法如下

                Student student = new Student() { Name = "張三", Age = 12 }; 學生 xuesheng = new 學生() { 姓名 = student.Name, 年齡 = student.Age };

因為這個兩個類比較簡單,所以我們采用這種方法看起來完全沒有問題,但是如果類的屬性很多,或者有很多這樣的類似的類需要轉換,如果我們還是這種手動的賦值,那么簡直就是hell。

這時,AutoMapper就能排上用場了。

步驟如下

1.通過nuget 引入AutoMapper

2.在項目根目錄下建立 Profiles文件夾(注意一定要寫對,否則采用依賴注入的方式AutoMapper自動加載配置信息掃不到該映射的),在下面新建一個StudentProfile.cs的類文件,代碼如下

 using AutoMapper; public class StudentProfile: Profile { public StudentProfile() { CreateMap<Student, 學生>(); } }

 

接下來有兩種方式來使用上面的映射配置:

方法一:采用依賴注入 (此處以WPF為例)

依賴

 public void ConfigureServices(IServiceCollection services) { //加載Profiles映射關系,自動查找Profiles文件夾下的映射類
 services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); ......其他代碼..... }

注入

private IMapper _mapper { get; set; } public MainWindowViewModel(IMapper mapper) { _mapper = mapper; } public void Test(Student student) { 學生 xuesheng = New 學生(); _mapper.Map(student, xuesheng); }

 

方法二:手動使用AutoMapper

Public Void Test ( Student student ) { ///手動加載映射關系
 var configuration = new MapperConfiguration(cfg => { cfg.AddProfile<Profiles.StudentProfile>(); }); ///手動映射
var mapper = configuration.CreateMapper(); 學生 xuesheng = mapper.Map<Student,學生>(student); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM