Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get logged in user in AutoMapper profile

I have asp.net core 2.0 web api project. Every Domain class inherits BaseEntity class:

public class BaseEntity
{
    public Guid Id { get; set; }

    public DateTime CreatedOn { get; set; }

    public Guid CreatedBy { get; set; }

    public DateTime ModifiedOn { get; set; }

    public Guid ModifiedBy { get; set; }
}

for converting view models to DTO-s I use AutoMapper.

I created two profiles, one for ViewModel to DTO and another for DTO to ViewModel.

In the profile where I map ViewModels to DTOs, I need that BaseEntity fields

    public Guid CreatedBy { get; set; }

    public Guid ModifiedBy { get; set; }

to be mapped from authorized user. I have already set up authentication, just need to access the authorized user object from AutoMapper profile class.

Is there any way I can do this?

like image 834
unixxx Avatar asked Nov 29 '25 07:11

unixxx


1 Answers

You will have to use custom value resolvers in AutoMapper to get your user object into the context.

Profile Configuration

Mapper.CreateMap<ViewModel, Dto>()
    .ForMember(d => d.CreatedBy, opt => opt.ResolveUsing((src, dest, destMember, res) => res.Context.Options.Items["CreatedBy"]));

When Calling Mapper

Mapper.Map<ViewModel, Dto>(src, opt => opt.Items["CreatedBy"] = this.createdByUserObject);
like image 116
Arun Selva Kumar Avatar answered Dec 02 '25 03:12

Arun Selva Kumar



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!