1

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.