3
votes

I am using AutoMapper to map between an entity and an Interface

First I created my mapping and checked it is valid.

AutoMapper.Mapper.CreateMap<User, IUserViewModel>();
AutoMapper.Mapper.AssertConfigurationIsValid();

Then I created a method that uses this mapping:

public IUserViewModel GetUser(int id)
{
      var user= _userRepository.GetByKey(id);

      var currentUser = Mapper.Map<User, IUserViewModel>(user);

      return currentUser;

}

I am using this method in another place of my code

 IUserViewModel myUser = XXXXX.GetUser(3);

This issue is this is myUser is always null.

However, when I debug my method and stop inside it juste before returning , I can see that my object currentSupplier is created and filled up correctly.

But when the method returns I get a null value.

I guess this has to do with the fact my object currentSupplier is created as Proxy<....>

Any help?

Thank you.

1
Hi, I have copied your code as you have it and it works fine for me. - Dave Walker

1 Answers

0
votes

Adding a full copy of my code that proves that the above works for me - couldnt fit it into the comments.

class Program
{
    static void Main(string[] args)
    {
        Program program = new Program();
        IUserViewModel myUser = program.GetUser(3);
        Console.WriteLine(myUser.Name);  // Prints Frank
        Console.Read();
    }

    public Program()
    {
        Mapper.CreateMap<User, IUserViewModel>();
        Mapper.AssertConfigurationIsValid();
    }

    private UserRepo _userRepository = new UserRepo();

    public IUserViewModel GetUser(int id)
    {
        var user = _userRepository.GetByKey(id);

        var currentUser = Mapper.Map<User, IUserViewModel>(user);

        return currentUser;
    }
}

public class UserRepo
{
    public User GetByKey(int id)
    {
        return new User { Name = "Frank" };
    }
}

public interface IUserViewModel
{
    string Name { get; set; }
}

public class User
{
    public string Name { get; set; }
}

Could you add some additional content to show where this is failing?