【问题标题】:ASP.Net MVC 3 AutoMapperASP.Net MVC 3 自动映射器
【发布时间】:2012-04-05 13:50:45
【问题描述】:

我正在使用 Entity Framework 4.1 和 Automapper 开发一个 ASP.Net MVC 3 Web 应用程序,以将我的对象的属性映射到 ViewModels,反之亦然。

我有一个名为 Shift 的类

public partial class Shift
{
    public Shift()
    {
        this.Locations = new HashSet<ShiftLocation>();
    }

    public int shiftID { get; set; }
    public string shiftTitle { get; set; }
    public System.DateTime startDate { get; set; }
    public System.DateTime endDate { get; set; }
    public string shiftDetails { get; set; }

    public virtual ICollection<ShiftLocation> Locations { get; set; }

}

还有一个名为 ViewModelShift 的 ViewModel

public class ViewModelShift
{
    public int shiftID { get; set; }

    [DisplayName("Shift Title")]
    [Required(ErrorMessage = "Please enter a Shift Title")]
    public string shiftTitle { get; set; }

    [DisplayName("Start Date")]
    [Required(ErrorMessage = "Please select a Shift Start Date")]
    public DateTime startDate { get; set; }

    [DisplayName("End Date")]
    [Required(ErrorMessage = "Please select a Shift End Date")]
    public DateTime endDate { get; set; }

    [DisplayName("Shift Details")]
    [Required(ErrorMessage = "Please enter detail about the Shift")]
    public string shiftDetails { get; set; }

    [DisplayName("Shift location")]
    [Required(ErrorMessage = "Please select a Shift Location")]
    public int locationID { get; set; }

    public SelectList LocationList { get; set; }

}

然后我在控制器中有以下代码

[HttpPost]
    public ActionResult EditShift(ViewModelShift model)
    {
            if (ModelState.IsValid)
            {
                Shift shift = _shiftService.GetShiftByID(model.shiftID);
                shift = Mapper.Map<ViewModelShift, Shift>(model);
             }
     }

效果很好,当变量“shift”第一次填充 Shift 详细信息时,延迟加载也会加载相关的“Locations”集合。

但是,一旦映射发生,shift.Locations 就等于 0。无论如何设置 AutoMapper,它只是将 ViewModel 类中的属性映射到班次而不删除位置集合?

一如既往地感谢大家。

【问题讨论】:

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


    【解决方案1】:

    Automapper 能够为创建的地图的特定成员指定选项。

    https://github.com/AutoMapper/AutoMapper/wiki/Configuration-validation

    试试这个:

     Mapper.CreateMap<ViewModelShift, Shift>()
           .ForMember(dest => dest.Locations, opt => opt.Ignore());
    

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多