2014-02-28 65 views
2

我在我的ASP.NET MVC4项目中使用AutoMapper。映射2类Question和QuestionViewModel时遇到问题。在这里我的两个模型类:AutoMapper:映射元组到元组

public class Question 
    { 
     public int Id { get; set; } 
     public string Content { get; set; } 
     public Tuple<int, int> GetVoteTuple() 
     { 
     "some code here" 
     } 
    } 

    public class QuestionViewModel 
    { 
     public int Id { get; set; } 
     public string Content { get; set; } 
     public Tuple<int, int> VoteTuple { get; set; } 
    } 

这里是我的控制器代码:

public class QuestionController: Controller 
    { 
     public ActionResult Index(int id) 
     { 

      Question question = Dal.getQuestion(id); 
      Mapper.CreateMap<Question, QuestionViewModel>() 
       .ForMember(p => p.VoteTuple, 
       m => m.MapFrom(
       s => s.GetVoteTuple() 
      )); 

      QuestionViewModel questionViewModel = 
         Mapper.Map<Question, QuestionViewModel>(question); 

      return View(questionViewModel); 

      } 
    } 

当我运行这段代码QuestionViewModelVoteTuple酒店空值。我如何映射2类与Tuple属性?

谢谢。

+0

您正在使用什么版本?此外,MapFrom片不是必需的,AutoMapper会自动映射GetFoo() - > Foo(不带Get的方法称为Get属性)。 –

回答

1

映射到元组是不可能在默认情况下,由于元组没有setter属性(他们只能通过构造函数初始化)。

你有2种选择:

1)创建Automapper自定义解析,然后使用.ResolveUsing方法在映射配置:.ForMember(p => p.VoteTuple, m => m.ResolveUsing<CustomTupleResolver>())

2)映射到一个属性/一类,而不是像这样的:

public class QuestionViewModel 
{ 
    public int Id { get; set; } 
    public string Content { get; set; } 
    public int VoteItem1 { get; set; } 
    public int VoteItem2 { get; set; } 
} 

然后:

.ForMember(p => p.VoteItem1, m => m.MapFrom(g => g.Item1)) 
.ForMember(p => p.VoteItem2, m => m.MapFrom(g => g.Item2)) 

你并不需要在你的视图模型中使用Tuple,所以我会推荐第二个选项。

编辑

我看你已经更新了你的代码,以便GetVoteTuple()是一个函数,而不是一个属性。在这种情况下,你可以轻松地适应这样的代码:

.ForMember(p => p.VoteItem1, m => m.MapFrom(g => g.GetVoteTuple().Item1)) 
.ForMember(p => p.VoteItem2, m => m.MapFrom(g => g.GetVoteTuple().Item2)) 
1

CreateMap调用是不正确的:

Mapper.CreateMap<Question, QuestionViewModel>() 
    .ForMember(p => p.VoteTuple, 
     m => m.MapFrom(
     s => s.GetVoteTuple() 
//-----------^ 
    )); 
+0

谢谢你安德鲁,我改变'问题' - >'s'但它仍然有空值。 –

+0

@ user3286476:你可以显示'GetVoteTuple()'的实现吗? –

0

尝试使用ResolveUsing代替MapFrom(和你的拉姆达使用通用s参数,而不是局部变量的引用的:

 Mapper.CreateMap<Question, QuestionViewModel>() 
      .ForMember(p => p.VoteTuple, 
      m => m.ResolveUsing(
      s => s.GetVoteTuple() 
     )); 

MapFrom使用直接映射属性由于您想从函数调用的结果中“映射”,因此ResolveFrom更多适当的。

此外,你应该只在您的应用程序通过Automapper调用CreateMap一次,通常是在Application_Start完成从元组global.asax

0

试试这个:

Mapper.CreateMap<Question, QuestionViewModel>() 
       .ForMember(p => p.VoteTuple,op=>op.MapFrom(v=>new Tuple<int,int>(v.GetVoteTuple.Item1,v.GetVoteTuple.Item2)));