【问题标题】:MVC-ViewModel + Automapper: How would use of Automapper look on my code if I would like to use it?MVC-ViewModel + Automapper:如果我想使用 Automapper,我的代码会如何使用?
【发布时间】:2012-02-23 11:51:08
【问题描述】:

我的项目首先使用 MVC-Viewmodel 和 EF 模型

这些是我用于索引视图的 Viewmodel:

public class IndexViewModel
{
    public List<QuestionViewModel> Questionlist { get; set; }
}

&

   public class QuestionViewModel
    {
       public string QuestionText { get; set; }
       public List<string> CoreValues { get; set; }
       public List<string> SubjectTypes { get; set; }
       public int QID { get; set; }

   }
}

这是我的控制器操作:

public ActionResult Index()
    {
       List<Question> ListQuestions = Arep.getallquestion();
       var model = new IndexViewModel();
       model.Questionlist = new List<QuestionViewModel>();
       foreach (var item in ListQuestions)
       {
           var QuestionViewModel = new QuestionViewModel();
           model.Questionlist.Add(QuestionViewModel);
           QuestionViewModel.QuestionText = item.QuestionText;
           QuestionViewModel.QID = item.QID;
           QuestionViewModel.CoreValues = new List<string>();
           foreach (var Corevalue in item.CoreValue)
           {
               QuestionViewModel.CoreValues.Add(Corevalue.Cname);   
           }
           QuestionViewModel.SubjectTypes = new List<string>();
           foreach (var SubjectType in item.SubjectType)
           {
               QuestionViewModel.SubjectTypes.Add(SubjectType.Sname);
           }
       }

        return View(model);
    }

我的视图 UI 所做的是显示与 CoreValue.CnameSubjectType.Sname 相关的带有 Questions.QuestionText 的列表。问题可以有多个 CoreValues 和 SubjectType。

我想知道这段代码在使用 Automapper 后的样子,非常感谢!

提前致谢!

最好的问候!

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 entity-framework mvvm automapper


    【解决方案1】:

    未经测试,但是:

    首先,您有 CreateMap 部分(通常在 global.asax.cs 中)

    Mapper.CreateMap<Question, QuestionViewModel>()
    .ForMember(m => m.CoreValues, opt => opt.MapFrom(s => s.CoreValue.Select(x => x.Cname)))
    .ForMember(m => m.SubjectTypes, opt => opt.MapFrom(s => s.SubjectType.Select(x => x.Sname)))
    

    然后在你的控制器中,

    var model = new IndexViewModel();
    model.Questionlist = Mapper.Map(Arep.getallquestions(), new List<QuestionViewModel>());
    return View(model);
    

    顺便说一句,您的控制器(没有自动映射器)的代码可以通过简单的 linq 查询更加简洁!

    【讨论】:

    • 我在我的 application_start 中添加了 createmap 部分,它工作得很好,谢谢! :)
    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多