i have a view model like this:
public class CityModel
{
public int Id { get; set; }
[Required]
public int ProvinceId { get; set; }
[Required]
public string Caption { get; set; }
public string Description { get; set; }
}
and an entity:
public class City : BaseEntity
{
public int ProvinceId { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
public virtual Province Province { get; set; }
}
and a BaseEntity:
public abstract class BaseEntity
{
public int Id { get; set; }
public DateTime CreatedOn { set; get; }
public string CreatedBy { set; get; }
public DateTime ModifiedOn { set; get; }
public string ModifiedBy { set; get; }
}
i want to map one object of type CityModel to on object of type City In Edit Action using AutoMapper ,
[HttpPost]
public ActionResult Edit(CityModel model)
{
if (ModelState.IsValid)
{
var entity = _cityRepository.GetCity(model.Id);
entity = model.ToEntity();
var operationStatus = _cityRepository.Edit(entity);
if (operationStatus.IsSuccess) operationStatus = _cityRepository.Save();
if (operationStatus.IsSuccess)
RedirectToAction("Index");
}
ViewBag.ProvinceId = new SelectList(_provinceRepository.Provinces, "Id", "Caption", model.ProvinceId);
return View(model);
}
The ToEntity is :
public static City ToEntity(this CityModel model)
{
return Mapper.DynamicMap<CityModel, City>(model);
}
and finally create map from CityModel To City Uses this Code:
Mapper.CreateMap<CityModel, City>()
.ForMember(des => des.Caption, op => op.MapFrom(src => src.Caption.ToPersianContent()))
.ForMember(des => des.Description, op => op.MapFrom(src => src.Description.ToPersianContent()));
when i want to map from CityModel To City , get City From Database. inherited data in city object are correct :
and After Mapping , i want to keep original inherited mapping and automapper ignore mapping this base properties, but null and default values are set to this properties: