我试图重构我的项目并使用automapper将视图模型映射到实体模型。这是我目前的代码。我使用过 Guid.NewGuid(), GetValueOrDefault()和 DateTime.Now 。如何在映射中编辑这些值?
var product = new Product
{
Id = Guid.NewGuid(),
Name = model.Name,
Price = model.Price.GetValueOrDefault(),
ShortDescription = model.ShortDescription,
FullDescription = model.FullDescription,
SEOUrl = model.SEOUrl,
MetaTitle = model.MetaTitle,
MetaKeywords = model.MetaKeywords,
MetaDescription = model.MetaDescription,
Published = model.Published,
DateAdded = DateTime.Now,
DateModified = DateTime.Now
};
然后这是我的地图代码
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Product, ProductCreateUpdateModel>().ReverseMap();
});
答案 0 :(得分:0)
告诉我,如果我理解你的话。您想要创建AutoMapper配置,但是您想要手动映射某些属性?在这种情况下,您可以执行以下操作:
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Product, ProductCreateUpdateModel>()
.ReverseMap()
.ForMember(product => product.Price, expression => expression.MapFrom(model => model.Price.GetValueOrDefault()))
.ForMember(product => product.DateAdded, expression => expression.UseValue(DateTime.Now))
.ForMember(product => product.DateModified, expression => expression.UseValue(DateTime.Now));
});
如果没有,请指出您的问题。