Reputation: 5105
I am developing an ASP.Net MVC 3 Web application using Entity Framework 4.1 and also Automapper to map properties from my Objects to ViewModels and vice-versa.
I have the following class called 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; }
}
And a ViewModel called ViewModelShift
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; }
}
I then have the following code in a Controller
[HttpPost]
public ActionResult EditShift(ViewModelShift model)
{
if (ModelState.IsValid)
{
Shift shift = _shiftService.GetShiftByID(model.shiftID);
shift = Mapper.Map<ViewModelShift, Shift>(model);
}
}
Which works fine, when the variable 'shift' is first populated with Shift details, lazy loading also loads the related collection of 'Locations'.
However, once the mapping has taken place, shift.Locations then equals to 0. Is there anyway to setup AutoMapper, that it just maps over the properties in the ViewModel class to the shift without removing the collection of Locations?
Thanks as ever everyone.
Upvotes: 0
Views: 551
Reputation: 657
Automapper has the ability to designate options for specific members of a created map.
https://github.com/AutoMapper/AutoMapper/wiki/Configuration-validation
Try this:
Mapper.CreateMap<ViewModelShift, Shift>()
.ForMember(dest => dest.Locations, opt => opt.Ignore());
Upvotes: 2