【问题标题】:Map ViewModel / partials with AutoMapper使用 AutoMapper 映射 ViewModel/partials
【发布时间】:2010-01-25 21:37:17
【问题描述】:

我已经创建了演示模型,我想将它(使用 AutoMapper)映射到 ViewModel。 ViewModel 是复合的 / 因为我正在使用部分,并且我想在其他视图/部分上重用例如 KeyboardsViewModel。

如何将此演示模型映射(设置映射)到 ViewModel?这是正确的方法吗?

谢谢!

public class MainPresentationModel : BasePresentationModel
{
  // Should map into the MainViewModel.Keyboards.Keyboards
  public int DefaultKeyboard { get; set; }
  // Should map into the MainViewModel.Keyboards.DefaultKeyboard
  public IList<Keyboard> Keyboards { get; set; }
  // Should map into the MainViewModel.Something
  public string Something { get; set; }
}

public class MainViewModel : BaseViewModel
{
  public KeyboardsViewModel Keyboards { get; set; }
  public string Something { get; set; }
}

public class KeyboardsViewModel
{
  public int DefaultKeyboard { get; set; }
  public IList<Keyboard> Keyboards { get; set; }
}

编辑: 尝试后我认为这是一种选择:

        Mapper.CreateMap<MainPresentationModel, MainViewModel>()
            .ForMember(d => d.Keyboards, opt => opt.MapFrom(src => src));
        Mapper.CreateMap<MainPresentationModel, KeyboardsViewModel>();

它似乎有效,但我不确定这是否是最佳/正确的方式......

【问题讨论】:

    标签: c# asp.net-mvc automapper


    【解决方案1】:

    这种方式绝对有效。您还可以为这些复合 UI 使用接口。例如,partial 可以接受 IKeyboardsViewModel,然后您就不必担心复杂的继承层次结构。然后,您可以只给每个部分主模型的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多