Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapster.Tool use codegen to generate mappers but not DTOs

Tags:

c#

mapster

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.

like image 723
Christopher Edwards Avatar asked Nov 04 '25 08:11

Christopher Edwards


1 Answers

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.

like image 157
Simon Hooper Avatar answered Nov 07 '25 01:11

Simon Hooper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!