0

Entity Framework 4.1 と Automapper を使用して ASP.Net MVC 3 Web アプリケーションを開発し、オブジェクトから ViewModel に、またはその逆にプロパティをマップしています。

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 は 0 に等しくなります。AutoMapper をセットアップする方法はありますか?それは、ViewModel クラスのプロパティをシフトにマッピングするだけで、Locations のコレクションを削除しませんか?

いつもありがとうございます。

4

1 に答える 1

2

Automapper には、作成されたマップの特定のメンバーのオプションを指定する機能があります。

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

これを試して:

 Mapper.CreateMap<ViewModelShift, Shift>()
       .ForMember(dest => dest.Locations, opt => opt.Ignore());
于 2012-04-05T14:03:41.203 に答える