Skip to main content
edited title
Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

is this implementation of the mapper pattern correct? Querying a database with Dapper

Source Link
xerxes
  • 327
  • 4
  • 14

is this implementation of the mapper pattern correct?

In the current project that I am working on, we are using dapper to query the database and sometime when mapping from dynamic types to concrete types we end up with a messy block of code.

I created a folder called mappers and have created an Interface<T>, an abstract class inheriting from that interface and I have also set up my IOC to map according to naming conventions so that I can inject my mappers through the constructor of my query classes.

public interface IMapper<out T>
    {
        T Map(SqlMapper.GridReader reader);
    }

    public abstract class MapperBase<T> : IMapper<T>
    {
        public abstract T Map(SqlMapper.GridReader reader);
    }

    public class UserDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class UserDtoMapper : MapperBase<UserDto>
    {
        public override UserDto Map(SqlMapper.GridReader reader)
        {
            return reader.Read().Select(x => new UserDto()
            {
                Id = x.Id,
                Name = x.Name
            }).SingleOrDefault();
        }
    }

    public class QueryObject
    {
        private IMapper<UserDto> userDtoMapper; 

        public QueryObject(IMapper<UserDto> userDtoMapper)
        {
            this.userDtoMapper = userDtoMapper;
        }

        public UserDto Query(int id)
        {
            ..........
             return userDtoMapper.Map(reader)
            ...
        }
    }