AutoMapper實體映射基本用法
AutoMapper安裝
在 Nuget 搜索即可安裝,目前筆者使用的版本是 10.1.1,AutoMapper 的程序集大約 280KB。
AutoMapper 主要功能是將一個對象的字段的值映射到另一個對象相應的字段中,AutoMapper 大家應該很熟悉,這里就不贅述了。
AutoMapper 基本使用
假如兩個如下類型:
public class TestA { public int A { get; set; } public string B { get; set; } // 剩下 99 個字段省略 } public class TestB { public int A { get; set; } public string B { get; set; } // 剩下 99 個字段省略 }
我們可以通過 AutoMapper 快速將 TestA 中所有字段的值復制一份到 TestB 中。
創(chuàng)建 TestA 到 TestB 的映射配置:
MapperConfiguration configuration = new MapperConfiguration(cfg => { // TestA -> TestB cfg.CreateMap<TestA, TestB>(); });
創(chuàng)建映射器:
IMapper mapper = configuration.CreateMapper();
使用 .Map()
方法將 TestA 中字段的值復制到 TestB 中。
TestA a = new TestA(); TestB b = mapper.Map<TestB>(a);
映射配置
上面我們用 cfg.CreateMap<TestA, TestB>();
創(chuàng)建了 TestA 到 TestB 的映射,在不配置的情況下,AutoMapper 默認會映射所有字段。
當然,我們可以在 MapperConfiguration
中,為每個字段定義映射邏輯。
MapperConfiguration 的構造函數定義如下:
public MapperConfiguration(Action<IMapperConfigurationExpression> configure);
這個 IMapperConfigurationExpression
是一個鏈式函數,可以為映射中的每個字段定義邏輯。
將上面的模型類修改為如下代碼:
public class TestA { public int A { get; set; } public string B { get; set; } public string Id { get; set; } } public class TestB { public int A { get; set; } public string B { get; set; } public Guid Id { get; set; } }
創(chuàng)建映射表達式如下:
MapperConfiguration configuration = new MapperConfiguration(cfg => { // TestA -> TestB cfg.CreateMap<TestA, TestB>() // 左邊是 TestB 的字段,右邊是為字段賦值的邏輯 .ForMember(b => b.A, cf => cf.MapFrom(a => a.A)) .ForMember(b => b.B, cf => cf.MapFrom(a => a.B)) .ForMember(b => b.Id, cf => cf.MapFrom(a => Guid.Parse(a.Id))); });
.ForMember()
方法用于創(chuàng)建一個字段的映射邏輯,有兩個表達式 ({表達式} , {表達式2})
,其中表達式1代表 TestB 映射的字段;表達式2代表這個字段的值從何處來。
表達式2有常用幾種映射來源:
.MapFrom()
從 TestA 取得;.AllowNull()
設置空值;.Condition()
有條件地映射;.ConvertUsing()
類型轉換;
這里筆者演示一下 .ConvertUsing()
的使用方法:
cfg.CreateMap<string, Guid>().ConvertUsing(typeof(GuidConverter));
這樣可以將 string 轉換為 Guid,其中 GuidConverter 是 .NET 自帶的轉換器,我們也可以自定義轉換器。
當然,即使不定義轉換器,string 默認也可以轉換成 Guid,因為 AutoMapper 比較機智。
對于其它內容,這里不再贅述,有興趣可查閱文檔。
映射檢查
假如 TestA 有的字段 TestB 沒有,則不復制;TestB 有的字段 TestA 中沒有,則此字段不做處理(初始化值)。
默認情況,TestA 跟 TestB 中的字段不太一致的話,可能有些地方容易造成忽略,開發(fā)者可以使用檢查器去檢查。
只需要在定義 MapperConfiguration
以及映射關系后,調用:
configuration.AssertConfigurationIsValid();
這個檢查方法,只應在 Debug 下使用。
當映射沒有被覆蓋時
你可以在 TestB 中增加一個 D 字段,然后啟動程序,會提示:
AutoMapper.AutoMapperConfigurationException
因為 TestB 中的 D 字段,沒有相應的映射。這樣,當我們在編寫映射關系時,就可以避免漏值的情況。
性能
剛使用 AutoMapper 時,大家可能會在想 AutoMapper 的原理,反射?性能如何?
這里我們寫一個示例用 BenchmarkDotNet
測試一下。
定義 TestA:
public class TestB { public int A { get; set; } public string B { get; set; } public int C { get; set; } public string D { get; set; } public int E { get; set; } public string F { get; set; } public int G { get; set; } public string H { get; set; } }
定義 TestB 的屬性同上。
[SimpleJob(runtimeMoniker: RuntimeMoniker.NetCoreApp31)] public class Test { private static readonly MapperConfiguration configuration = new MapperConfiguration(cfg => { cfg.CreateMap<TestA, TestB>(); }); private static readonly IMapper mapper = configuration.CreateMapper(); private readonly TestA a = new TestA { A = 1, B = "aaa", C = 1, D = "aaa", E = 1, F = "aaa", G = 1, H = "aaa", }; [Benchmark] public TestB Get1() { return new TestB { A = a.A, B = a.B, C = a.C, D = a.D, E = a.E, F = a.F, G = a.G, H = a.H }; } [Benchmark] public TestB Get2() { return mapper.Map<TestB>(a); } [Benchmark] public TestA Get3() { return mapper.Map<TestA>(a); } }
測試結果如下:
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042 Intel Core i7-3740QM CPU 2.70GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=5.0.200-preview.20601.7 [Host] : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT .NET Core 3.1 : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT Job=.NET Core 3.1 Runtime=.NET Core 3.1 | Method | Mean | Error | StdDev | |------- |----------:|---------:|---------:| | Get1 | 16.01 ns | 0.321 ns | 0.284 ns | | Get2 | 204.63 ns | 3.009 ns | 2.349 ns | | Get3 | 182.53 ns | 2.215 ns | 2.072 ns | Outliers Test.Get1: .NET Core 3.1 -> 1 outlier was removed (25.93 ns) Test.Get2: .NET Core 3.1 -> 3 outliers were removed (259.39 ns..320.99 ns)
可以看到,性能相差了 10 倍。
在提高靈活性等情況下,會犧牲一些性能,主要不是大量計算的情況下,并不會有太大性能問題。
Profile 配置
除了 MapperConfiguration 外,我們還可以使用繼承 Profile 的方式定義映射配置,實現(xiàn)更小粒度的控制以及模塊化,ABP 框架中正是推薦了 AutoMapper 的此種方式,配合模塊化。
示例如下:
public class MyProfile : Profile { public MyProfile() { // 這里就不贅述了 base.CreateMap<TestA, TestB>().ForMember(... ...); } }
如果我們使用 ABP,那么每個模塊都可以定義一個 Profiles 文件夾,在里面定義一些 Profile 規(guī)則。
一種映射定義一個 Profile 類?這樣太浪費空間了;一個模塊定義一個 Profile 類?這樣太雜了。不同的程序有自己的架構,按照項目架構選擇 Profile 的粒度就好。
依賴注入
AutoMapper 依賴注入很簡單,前面我們學會了 Profile 定義配置映射,這樣我們就可用很方便地使用依賴注入框架處理映射。
①我們在 ASP.NET Core 的 StartUp 或者 ConsoleApp 的 IServiceCollection 中,注入:
services.AddAutoMapper(assembly1, assembly2 /*, ...*/);
AutoMapper 會自動掃描 程序集(Assembly) 中類型,把繼承了 Profile 的類型提取出來。
②如果你想更小粒度地控制 AutoMapper ,則可以使用:
services.AddAutoMapper(type1, type2 /*, ...*/);
.AddAutoMapper()
注冊的 AutoMapper 的生命周期為 transient
。
③如果你不喜歡 Profile ,那么還可以繼續(xù)使用前面的 MapperConfiguration
,示例代碼如下:
MapperConfiguration configuration = new MapperConfiguration(cfg => { cfg.CreateMap<TestA, TestB>(); }); services.AddAutoMapper(configuration);
之后我們可以通過依賴注入使用 AutoMapper,使用形式是 IMapper 類型:
public class HomeController { private readonly IMapper _mapper; public HomeController(IMapper mapper) { _mapper = mapper; } }
IMapper 有一個 .ProjectTo<>()
方法,可以幫助處理 IQueryable
查詢。
List<TestA> a = new List<TestA>(); ... ... _ = mapper.ProjectTo<TestB>(a.AsQueryable()).ToArray();
或者:
_ = a.AsQueryable().ProjectTo<TestB>(configuration).ToArray();
還可以配置 EFCore 使用:
_ = _context.TestA.ProjectTo<TestB>(configuration).ToArray(); _ = _context.TestA.ProjectTo<TestB>(mapper.ConfigurationProvider).ToArray();
表達式與 DTO
AutoMapper 有著不少拓展,這里筆者介紹一下 AutoMapper.Extensions.ExpressionMapping,在 Nuget 里面可以搜索到。
AutoMapper.Extensions.ExpressionMapping
這個拓展實現(xiàn)了大量的表達式樹查詢,這個庫實現(xiàn)了 IMapper 拓展。
假如:
public class DataDBContext : DbContext { public DbSet<TestA> TestA { get; set; } } ... ... DataDBContext data = ... ...
配置:
private static readonly MapperConfiguration configuration = new MapperConfiguration(cfg => { cfg.AddExpressionMapping(); cfg.CreateMap<TestA, TestB>(); });
假如,你要實現(xiàn)過濾功能:
// It's of no use Expression<Func<TestA, bool>> filter = item => item.A > 0; var f = mapper.MapExpression<Expression<Func<TestA, bool>>>(filter); var someA = data.AsQueryable().Where(f); // data is _context or conllection
當然,這段代碼沒有任何用處。
你可以實現(xiàn)自定義的拓展方法、表達式樹,更加便利地對 DTO 進行操作。
下面是示例:
public static class Test { // It's of no use //public static TB ToType<TA, TB>(this TA a, IMapper mapper, Expression<Func<TA, TB>> func) //{ // //Func<TA, TB> f1 = mapper.MapExpression<Expression<Func<TA, TB>>>(func).Compile(); // //TB result = f1(a); // return mapper.MapExpression<Expression<Func<TA, TB>>>(func).Compile()(a); //} public static IEnumerable<TB> ToType<TA, TB>(this IEnumerable<TA> list, IMapper mapper, Expression<Func<TA, TB>> func) { var one = mapper.MapExpression<Expression<Func<TA, TB>>>(func).Compile(); List<TB> bList = new List<TB>(); foreach (var item in list) { bList.Add(one(item)); } return bList; } }
當你查詢時,可以這樣使用這個拓展:
_ = _context.TestA.ToArray().ToType(mapper, item => mapper.Map<TestB>(item));
到此這篇關于AutoMapper實體映射基本用法的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
asp.net配置會話狀態(tài)Session實現(xiàn)代碼
在Web應用程序中,都會有一個Web.config文件來配置當前Web項目。其中包括關于會話狀態(tài)Session的配置2012-10-10asp.net中利用Jquery+Ajax+Json實現(xiàn)無刷新分頁的實例代碼
本篇文章主要是對asp.net中利用Jquery+Ajax+Json實現(xiàn)無刷新分頁的實例代碼進行了介紹,需要的朋友可以過來參考下,需要對大家有所幫助2014-02-02visual studio 2019使用net core3.0創(chuàng)建winform無法使用窗體設計器
這篇文章主要介紹了visual studio 2019使用net core3.0創(chuàng)建winform無法使用窗體設計器,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03