我有一个模特
public class Product : BaseEntity
{
private string _name;
public string Name
{
get { return _name; }
private set{_name = value;}
}
public decimal Price { get; set; }
public double Weight { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public double Depth { get; set; }
public DateTime DateAdded { get; set; }
...
public string GeneralInfo {get{//some get logic}...}
}
和View模型:
public sealed class ProductDetailsModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public double Weight { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public double Depth { get; set; }
...
public string GeneralInfo {get;set;}
}
和控制器:
public class ProductController : Controller
{
...
public ActionResult Details(int id)
{
var product = _productRepository.GetProduct(id);
var productViewModel = Mapper.Map<ProductDetailsModel>(product);
return View(productViewModel);
}
...
}
一切都很好,但是......我有一些产品模型常规信息属性的逻辑,它从数据库中获取此一般信息,有时,当产品没有常规信息时,此属性返回null。我需要的是从可用的属性生成替代的一般信息,如With,Height等。像:
private string GenerateGeneralInfoFromProductProperties()
{
var generalInfoStringBuilder = new StringBuilder();
generalInfoStringBuilder.Append(@"<b>Width: </b>").Append(Width).Append("</br>");
generalInfoStringBuilder.Append(@"<b>Weight: </b>").Append(Weight).Append("</br>");
...
return generalInfoStringBuilder.ToString();
}
如果我将此逻辑添加到产品型号......
public class Product : BaseEntity
{
...
public string GeneralInfo
{
get
{
var gInfo = getGeneralInfoFromBD();
if (gInfo==null)
gInfo = GenerateGeneralInfoFromProductProperties();
return gInfo;
}
set { SetPropertyValue(ProductPropertyType.GeneralInfo, value); }
}
}
一切正常,但它会是错误和不合逻辑的,因为我有一个用于表示产品细节的视图模型,所以我想将这个逻辑添加到视图模型中,但我的视图模型实例是由mapper,Product view创建的model没有构造函数来传递产品实例来获取它的一般信息,因为正如我所说,它在构造函数中没有必要。如何添加此“如果为null的常规信息”将逻辑替换为映射器或查看模型?
答案 0 :(得分:0)
尝试AfterMap
Automapper.CreateMap<Product,ProductDetailsModel>()
.AfterMap((p,pm) => {
// now you have access to both objects, so you can do whatever you please
});