Search code examples
c#mapster

Mapster.Tool use codegen to generate mappers but not DTOs


Can I use Mapster.Tool to generate Mappers without also generating the class that I'm mapping to? I have a typical Domain objects to and from DTOs scenario but the sample code here

https://github.com/MapsterMapper/Mapster/tree/master/src/Sample.CodeGen

and the documentation here

https://github.com/MapsterMapper/Mapster/wiki/Mapster.Tool

both focus on generating the DTOs from the Domain objects, either by annotating them with attributes or using configuration. There is configuration to create DTOs that are CRU specific but I'd still rather create my own DTOs but not have to create my own mappings.


Solution

  • Yes you can - take a look at the interface based code gen documented here.

    This allows you to define an interface that will generate a mapper based on existing classes.

    From there you can choose how to consume the mapper that's generated. Register in services and then use DI being one way.

    Here is a quick example:

        [Mapper]
        public interface IContactMapper
        {
            ContactDetailVm MapTo(Contact contact);
        }
    

    Would result in

        public partial class ContactMapper : IContactMapper
        {
            public ContactDetailVm MapTo(Contact p2)
            {
                return p2 == null ? null : new ContactDetailVm()
                {
                    Id = p2.Id,
                    Created = p2.Created,
                    LastUpdate = p2.LastUpdate,
                    Title = p2.Title,
                    FirstName = p2.FirstName,
                    LastName = p2.LastName,
                    PreferredName = p2.PreferredName,
                    BirthYear = p2.BirthYear
                };
            }
        }
    

    I don't believe you can use the tool to generate the mapping extension methods for existing entities however. At least im not aware it can be done in v6.