1

我有一个这样的视图模型:

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; }
}

和一个实体:

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; }
}

和一个 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; }
}

我想使用 AutoMapper 在 Edit Action 中将 CityModel 类型的一个对象映射到 City 类型的对象上,

[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);
}

ToEntity 是:

public static City ToEntity(this CityModel model)
{
    return Mapper.DynamicMap<CityModel, City>(model);
}

最后创建从 CityModel 到 City 的地图使用此代码:

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()));

当我想从 CityModel 映射到 City 时,从数据库中获取 City。城市对象中的继承数据是正确的:

映射前

和 Mapping 之后,我想保留原始继承的映射和 automapper 忽略映射此基本属性,但 null 和默认值设置为此属性:

映射后

4

1 回答 1

2

我相信您在“ToEntity”中调用了错误的重载。您必须传入现有实体:

 DynamicMap<TSource, TDestination>(TSource source, TDestination destination)
于 2013-04-28T23:12:57.143 回答