MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.38k stars 331 forks source link

Easy mapping to differently named properties #362

Closed TimBandelin closed 1 year ago

TimBandelin commented 3 years ago

So I was working with Mapster on an API that communicates with a database using EF Core. I have a class that looks something like this:

    internal class MyObjectEntity
    {
       public int Id { get; set; }
       public string Name { get; set; }
    }

The connections to the database are managed in a class library, and because I don't want to have my database objects flying around somewhere outside, I have an additial class for communication:

     public sealed class MyObject
     {
       public int Id { get;}
       public string Name { get;}

       public MyObject(int id, string name)
       {
          Id = id;
          Name = name;
       }
     }

The API (ASP.NET) receives and gives instances of MyObject when communicating with the database library. But because these are implementation detail, the API send/receives special DTOs when communication with the frontend, similar to this:

     public class MyObjectDto
     {
        public int Id { get; }
        public string DifferentName { get; set; }

        public MyObjectDto(int id, string differentName)
        {
           Id = id;
           DifferentName = differentName;
        }
     }

Now, to map between these I use Mapster. There is obviously no problem with mapping between MyObject and MyObjectEntity, but when I want to map from MyObjectDto to MyObject and the other way around, I can apply the AdaptMember attribute to the properties. But when I put AdaptMember("DifferentName") to the Name-property of MyObject, the value turns into null whenn mapping MyObject to MyObjectEntity.

The attribute shouldn't override the mapping entirely, so it is possible to map MyObject to both MyObjectEntity and MyObjectDto, only using the AdaptMember attribute when it can't find a property called "Name".

andrerav commented 2 years ago

@TimBandelin For mapping scenarios like this you may want to consider using mapping configuration with rule based settings as described here: https://github.com/MapsterMapper/Mapster/wiki/Configuration#rule-based-settings. Can you take a look and see if this solves your problem?

andrerav commented 1 year ago

No feedback, assuming this is solved. Please let me know if this is still an issue with the latest version.