使用Automapper将视图模型映射到EF的实体,同时忽略空值

时间:2016-10-05 09:53:12

标签: c# asp.net entity-framework automapper

我正在尝试将视图模型映射到EF中的实体。到目前为止,我已经可以将所有属性从viewmodel映射到实体,但我试图忽略所有null属性(viewmodel中的数据来自一个表单,我不想放置{{1} }例如pk)。我希望能够做到这样的事情:

null

这是我到目前为止所提出的:

IUserDetails objUserDetails = GetDataFromForm();
var user = db.Users.FirstOrDefault();
user.UpdateUser(objUserDetails);

正如您所看到的,我在public static class UserExtensions { public static void UpdateUser(this IUser user, IUserDetails userDetails) { var config = new MapperConfiguration(cfg => { cfg.CreateMap<IUserDetails, IUser>() .UseDestinationValue() .IgnoreNullValues() .ForMember(dest => dest.AddressLine1, opt => opt.MapFrom(src => src.Address1)) .ForMember(dest => dest.AddressLine2, opt => opt.MapFrom(src => src.Address2)) .ForMember(dest => dest.LName, opt => opt.MapFrom(src => src.LastName)) .ForMember(dest => dest.UserGUID, opt => opt.MapFrom(src => src.GUID)); }); var mapper = config.CreateMapper(); mapper.Map<IUserDetails, IUser>(userDetails, user); } private static IMappingExpression<TSource, TDest> UseDestinationValue<TSource, TDest>(this IMappingExpression<TSource, TDest> expression) { expression.ForAllMembers(opt => opt.UseDestinationValue()); return expression; } private static IMappingExpression<TSource, TDest> IgnoreNullValues<TSource, TDest>(this IMappingExpression<TSource, TDest> expression) { expression.ForAllMembers(opt => opt.Condition((src, dest, srcVal, destVal, c) => { Debugger.Break(); return srcVal != null; })); return expression; } } 中放置了一个断点,当我调试代码时,我可以看到IgnoreNullValues()绝不是srcVal,但所有其他值看起来都是好。我错过了什么?

更新

显然这是由于bug in 5.1.1,降级到5.0.2使一切正常。

0 个答案:

没有答案