Msa*_*m85 263 c# model viewmodel automapper object-object-mapping
我正在使用Automapper,我有以下场景:类OrderModel有一个名为'ProductName'的属性,它不在数据库中.所以当我尝试使用以下方法进行映射时:
Mapper.CreateMap<OrderModel, Orders>();
Run Code Online (Sandbox Code Playgroud)
它会生成一个异常:
"Project.ViewModels.OrderModel上的以下1个属性未映射:'ProductName'
我已经阅读了AutoMapper的Wiki for Projections相反的情况(额外的属性在目的地,而不是在源,这实际上是我的情况)
如何避免使用automapper来映射此属性?
sma*_*man 429
来自吉米博加德: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());
Ste*_*uts 226
我可能是一个完美主义者; 我不太喜欢ForMember(...,x => x.Ignore())语法.这是一件小事,但对我来说很重要.我写了这个扩展方法,使它更好一点:
public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> map,
Expression<Func<TDestination, object>> selector)
{
map.ForMember(selector, config => config.Ignore());
return map;
}
Run Code Online (Sandbox Code Playgroud)
它可以像这样使用:
Mapper.CreateMap<JsonRecord, DatabaseRecord>()
.Ignore(record => record.Field)
.Ignore(record => record.AnotherField)
.Ignore(record => record.Etc);
Run Code Online (Sandbox Code Playgroud)
您也可以重写它以使用它params,但我不喜欢带有大量lambda的方法的外观.
Ric*_*ard 79
你可以这样做:
conf.CreateMap<SourceType, DestinationType>()
.ForSourceMember(x => x.SourceProperty, y => y.Ignore());
Run Code Online (Sandbox Code Playgroud)
Gui*_*ume 28
现在(AutoMapper 2.0)是一个IgnoreMap属性,我将使用它而不是流畅的语法,这是一个有点沉重的恕我直言.
Sté*_*ane 28
对于任何尝试自动执行此操作的人,您可以使用该扩展方法忽略目标类型上的非现有属性:
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
&& x.DestinationType.Equals(destinationType));
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
Run Code Online (Sandbox Code Playgroud)
用作如下:
Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();
Run Code Online (Sandbox Code Playgroud)
感谢Can Gencer提示:)
来源:http: //cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/
Lor*_*sen 21
将视图模型映射回域模型时,简单地验证源成员列表而不是目标成员列表可以更加清晰
Mapper.CreateMap<OrderModel, Orders>(MemberList.Source);
Run Code Online (Sandbox Code Playgroud)
现在Ignore(),每次我向域类添加属性时,我的映射验证都不会失败,需要另一个.
| 归档时间: |
|
| 查看次数: |
186211 次 |
| 最近记录: |