在ABP中靈活使用AutoMapper

2021-09-27 17:47:17 字數 3029 閱讀 9586

該文章是系列文章 基於.netcore和abp框架如何讓windows服務執行quartz定時作業 的其中一篇。

最多遇到的場景,應該是介面返回的dto和資料庫entity,出於敏感資訊保護或者減少介面返回資料等等的原因,dto返回的屬性或者字段有所刪減,也就是說需要對映的屬性或者字段屬性名稱一致。

dto和entity名稱不一致,甚至型別不同,相互轉換時甚至需要對資料有處理。

下面的例子就是字段屬性基本一致。

public class order

public string phonenumber

}public class orderdto

}

或者 public class myjobcoremodule : abpmodule

你可以通過屬性automap, automapfrom, automapto指定對映關係

改造上面的之前的例子

[automapfrom(typeof(order))]

public class orderdto

}

或者

[automapto(typeof(orderdto))]

public class order

public string phonenumber

}

但是屬性的使用場景比較窄,稍微複雜一點的場景就無法滿足,比如,指定忽略一些字段,或者欄位名稱不同需要顯示指定。

public class myjobcoremodule : abpmodule

); }}

忽略字段

config.createmap()

.formember(u => u.phonenumber, options => options.ignore());

欄位名不一致

orderdto增加手機號欄位tel,對映order欄位phonenumber

public class orderdto

public string tel

}

config.createmap()

.formember(u => u.tel, options => options.mapfrom(input => input.phonenumber));

需要對欄位進行處理後返回

比如,隱藏11位手機號的中間4位

private static string hidetel(string input)

var outreplace = regex.replace(input, "(\\d)\\d(\\d)", "$1****$2");

return outreplace;

}

config.createmap()

.formember(u => u.tel, options => options.mapfrom(input => hidetel(input.phonenumber)));

拼接對映

又比如orderdto新增郵寄位址和收貨位址

namespace demo.myjob.entity.dto

public string tel

public string postaladdress

public string deliveryaddress

}}

order的相關表orderaddress型別定義

namespace demo.myjob.entity

public string postaladdress

public string deliveryaddress

}}

這時就需要orderaddress和order的資料相結合對映orderdto,怎麼實現呢?借助元組tuple。

config.createmap<(order, orderaddress), orderdto>()

.formember(u => u.tel, options => options.mapfrom(input => hidetel(input.item1.phonenumber)))

.formember(u => u.ordername, options => options.mapfrom(input => input.item1.ordername))

.formember(u => u.postaladdress, options => options.mapfrom(input => input.item2.postaladdress))

.formember(u => u.deliveryaddress, options => options.mapfrom(input => input.item2.deliveryaddress))

;

需要自定義的對映關係過多時,會使得preinitialize變大,不便於管理和檢視。

public override void preinitialize()

);}

using system.text.regularexpressions;

using demo.myjob.entity;

using demo.myjob.entity.dto;

var outreplace = regex.replace(input, "(\\d)\\d(\\d)", "$1****$2");

return outreplace;}}

}

修改preinitialize

public class myjobcoremodule : abpmodule

); }

}

config.addprofiles(typeof(myjobcoremodule));

在ABP中使用SQLite

使用abp連線sqlite時出現下面錯誤 system.data.entity.core.entityexception the underlying provider failed on open.內部異常 argumentexception isolationlevel 找了好久才解決,記錄一下...

在ABP模板工程中使用MySQL

2 在windows上安裝mysql,這裡不多說,我用的是mysql installer 5.5.21.0 3 開啟模板專案,還原nuget包先 開啟專案後,在 程式包管理器控制平台 中選擇 entityframwork以及 web專案 號為你的專案名稱字首 install package mysq...

python中靈活使用公式

迴圈中的if else a 3 if false else 5 print a if false a 3 else a 5 邏輯運算中and or 前面的表示式為真,才會執行後面的表示式 a true and 3 print a 前面的表示式為假,後面的表示式不需要執行 b false and 5 ...