0

As I'm having a single DTO, we use DTOs for GET, PUT and POST http method in our Web API.

To make simple we have ActivityDO:

public ActivityDTO
{
   public int Id;
   public string Name;
   public string CategoryName;
   public DateTime DateCreated;
   public DateTime DateModified;
}

The challenge is when you only have a single DTO for handling multiple conditions i.e. post/get/put method, the mapping as follow:

private MapperConfiguration configuration = new MapperConfiguration(cfg => {
            cfg.CreateMap<ActivityDTO, Activity>()
                .ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()))
                .ForMember(dst => dst.CategoryId, opt => opt.MapFrom(src => GetCategoryId(HttpContext.Current.User.Identity.GetUserId(), src.CategoryName)))
                .ForMember(dst => dst.DateCreated, opt => opt.MapFrom(src => DateTime.UtcNow))
                .ForMember(dst => dst.DateModified, opt => opt.MapFrom(src => DateTime.UtcNow));
        });

I want to IGNORE the mapping for DateCreated if we do the update and we can do the condition if the id <= 0, the rest is allowed to mapping for DateCreated.

Is this possible? Would rather to have a seperate DTOs between GET/POST (Add) VS PUT (Update)? Is there any better solution to handle this DateCreated VS DateModified thingy?

I'm appreciated your feedback/comment.

dcpartners
  • 5,176
  • 13
  • 50
  • 73

1 Answers1

1

This is the way to add conditions. Is that what you are looking for?

private MapperConfiguration configuration = new MapperConfiguration(cfg => {
    cfg.CreateMap<ActivityDTO, Activity>()
        .ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()))
        .ForMember(dst => dst.CategoryId, opt => opt.MapFrom(src => GetCategoryId(HttpContext.Current.User.Identity.GetUserId(), src.CategoryName)))
        .ForMember(dst => dst.DateCreated, opt => opt.MapFrom(src => src.Condition(src.DateCreated != null)))
        .ForMember(dst => dst.DateModified, opt => opt.MapFrom(src => DateTime.UtcNow));
        });

I used src.DateCreated != null but you can specify any condition using the src.Condition() and the variable will only be mapped when the condition is met.

Also

You can use AutoMapper's PreCondition

var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<Foo,Bar>()
    .ForMember(dest => dest.baz, opt => {
        opt.PreCondition(src => (src.baz >= 0));
        opt.MapFrom(src => {

        });
    });
});
Bosco
  • 1,536
  • 2
  • 13
  • 25
  • After looking at this further, I decide to make it simple and the handling the condition for updating DateCreated VS not updating etc etc ... it needs to be done via overriding SaveChangesAsync / SaveChange instead. Means the mapping it's simple and it what supposed to do not putting some logic into. – dcpartners Sep 21 '19 at 22:52