Data transfer object pattern

后端 未结 3 1010
情歌与酒
情歌与酒 2020-12-08 16:34

i\'m sorry i\'m newbie to enterprise application as well as the design pattern. might be this question occcur lack of knowledge about design pattern. i found that its better

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 16:37

    You should really take a look at AutoMapper.

    http://automapper.org

    This is a piece of software that you can include in your solution that will automatically map values from one class to another.

    It'll map properties with the same name automatically, and is also pretty smart when it comes to child objects. However, it also offers complete mapping control when you need it.

    EDIT

    Couple of examples to show how AutoMapper works. Please note I'd never code like this in real life. Brevity!

    Example classes.

    // Common scenario.  Entity classes that have a connection to the DB.
    namespace Entities 
    {
       public class Manager
       {
          public virtual int Id { get; set; }
          public virtual User User { get; set; }
          public virtual IList Serfs { get; set; }
       }
    
       public class User
       {
          public virtual int Id { get; set; }
          public virtual string Firstname { get; set; }
          public virtual string Lastname { get; set; }
       }
    }
    
    
    
    // Model class - bit more flattened
    namespace Models 
    {
       public class Manager 
       {
          public int Id { get; set; }
          public string UserFirstname { get; set; }
          public string UserLastname { get; set; }
          public string UserMiddlename { get; set; }
       }
    }
    

    Typically, you'd have a part of your project to configure all your AutoMapping. With the examples I've just given, you can configure a map between Entities.Manager and Models.Manager like so:-

    // Tell AutoMapper that this conversion is possible
    Mapper.CreateMap();
    

    Then, in your code, you'd use something like this to get a new Models.Manager object from the Entity version.

    // Map the class
    var mgr = Map
      ( repoManager, new Models.Manager() );
    

    Incidentally, AM is smart enough to resolve a lot of properties automatically if you name things consistently.

    Example above, UserFirstname and UserLastname should be automatically populated because:-

    • Manager has a property called User
    • User has properties called Firstname and Lastname

    However, the UserMiddlename property in Models.Manager will always be blank after a mapping op between Entities.Manager and Models.Manager, because User does not have a public property called Middlename.

提交回复
热议问题