c# - How do I map a model with nested properties to a flat Dto? -



c# - How do I map a model with nested properties to a flat Dto? -

i'm trying create mapping our entity models dto i'm failing everytime in trying create mapping.

i have 2 domain classes. simplification of our model (device instance has lot more properties represent bunch of different things):

class device { public int name {get; set;} } class deviceaccesstoken { public device device {get; set;} public string key {get; set;} public string secret {get; set;} }

i want map deviceaccesstoken instances devicedto (also simplified, has of fields nowadays in original device model):

class devicedto { public int name {get; set;} public string key {get; set;} public string secret {get; set;} }

is there way create mapping without explicitly specifying fields of device domain model in mapping?

this want, represented automapper profile:

class devicemappingprofile : profile { protected override void configure() { this.createmap<deviceaccesstoken, devicedto>(); this.createmap<device, devicedto>() .formember(dest => dest.key, opt => opt.ignore()) .formember(dest => dest.secret, opt => opt.ignore()); } }

the .forallmembers phone call failed effort create work, must not function envisioned it.

i understand specifying every property of device in deviceaccesstoken->devicedto mapping, nightmare , redundant since names same.

"is there way create mapping without explicitly specifying fields of device domain model in mapping?"

yes, can utilize naming conventions in dto object , prevent having come in them in create map.

as example:

your values key , secret exist in deviceaccesstoken , devicedto not need mapped. device nested object dto can utilize convention of devicename.

example:

using system; using automapper; class device { public string name {get; set;} } class deviceaccesstoken { public device device {get; set;} public string key {get; set;} public string secret {get; set;} } class devicedto { public string devicename {get; set;} public string key {get; set;} public string secret {get; set;} } public class programme { public void main() { // configure automapper mapper.createmap<deviceaccesstoken, devicedto>(); var dat = new deviceaccesstoken { device = new device { name = "dev name" }, key = "key", secret = "secret" }; var dto = mapper.map<devicedto>(dat); console.writeline(dto.devicename); console.writeline(dto.key); console.writeline(dto.secret); } }

working fiddle

c# .net automapper dto convention-over-configur

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -