【问题标题】:Automapper : Mapping to an InterfaceAutomapper:映射到接口
【发布时间】:2011-10-31 08:56:54
【问题描述】:

我正在使用 AutoMapper 在实体和接口之间进行映射

首先我创建了我的映射并检查它是否有效。

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

然后我创建了一个使用这个映射的方法:

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

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

      return currentUser;

}

我在我的代码的另一个地方使用这个方法

 IUserViewModel myUser = XXXXX.GetUser(3);

这个问题是 myUser 始终为空。

但是,当我调试我的方法并在返回之前停止它时,我可以看到我的对象 currentSupplier 已正确创建并填充。

但是当方法返回时,我得到一个空值。

我想这与我的对象 currentSupplier 被创建为 代理<....>

有什么帮助吗?

谢谢。

【问题讨论】:

  • 嗨,我已经复制了你的代码,它对我来说很好。

标签: interface automapper


【解决方案1】:

添加我的代码的完整副本以证明上述内容对我有用 - 无法将其放入 cmets。

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; }
}

您能否添加一些额外的内容来说明失败的地方?

【讨论】:

    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2017-04-07
    • 2011-07-31
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    相关资源
    最近更新 更多