First, preface
DTO (Data Transfer object) Data Transfer object, note the keyword "data" two words, is not an Object Transfer object (Objects Transfer objects), so just transfer data, does not contain domain business processing, although the purpose is only to transfer data, But itself is actually the object, complete the transformation between the domain object, just like the value object mentioned above, in a sense the DTO can be regarded as a collection of value objects, but is a mapping between the domain objects, and does not contain any business logic.
Why use DTOs? The main reason is to isolate the domain model, make changes to the domain models without affecting the UI, and maintain the security of the domain model without exposing the business logic. There is in the distributed mode, different scenarios using the same data structure has different requirements, and we have to do some data transformation, it is very cumbersome, if we do in the early stages of the DTO analysis, so we will save a lot of things, and will not affect the entire project business process, It is also convenient to extend the project later.
Second, the example code
Add a automapper reference using the NuGet package first
1. Create an Entity object
Public class User { publicint UserID; Public string UserName; Public string Sex; Public string Address; }
2. Creating a DTO entity object for the UI
Public class Userdto { publicint ID; Public string Name; Public string Sex; Public string Address; Public string Remark; }
3. Invoke the instance and remember to use it.
classProgram {Static voidMain (string[] args) { //Initializing entity ObjectsUser User =NewUser () {userid=666, username="Xiao Ke", sex="male", address="AAABBBCCC"}; //Configure AutoMapper//since some of the field names in the Userdto and user classes do not correspond, you can initially map the propertiesMapper.initialize (i ={I.createmap<user, Userdto> ()//Creating Mappings. Formember (udto = udto.id, U = u.mapfrom (A =A.userid)) . Formember (Udto= = udto.name, U = u.mapfrom (A =a.username)) . Formember (Udto= = udto.address, U = u.mapfrom (a = A.address.toupper ()))//turn letters into uppercase and then assign to DTOs. Formember (udto = udto.remark, u = U.ignore ());//There is no remark in the user class, and userdto exists, ignoring the property with ignore (), and the string type defaults to null }); //Call map method returns DTO data Transfer objectUserdto userdto = Mapper.map<user, userdto>(user); } }
Results:
AutoMapper of the DTO Learning Series (i)