Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 :

Before Mapping

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:

After Mapping

share|improve this question

1 Answer 1

up vote 1 down vote accepted

I believe you are calling the wrong overload in "ToEntity". You have to pass in the existing entity:

 DynamicMap<TSource, TDestination>(TSource source, TDestination destination)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.