C# AutoMapper在源属性的条件下将目标设置为null
我在两个对象之间映射,根据源的条件,我希望目标为空 例如,以下是类:C# AutoMapper在源属性的条件下将目标设置为null,c#,automapper,C#,Automapper,我在两个对象之间映射,根据源的条件,我希望目标为空 例如,以下是类: public class Foo { public int Code { get; set; } public string Name { get; set; } } public class Bar { public string Name { get; set; } public string Type { get; set; } } 还有我的地图: Mapper.CreateMap&
public class Foo
{
public int Code { get; set; }
public string Name { get; set; }
}
public class Bar
{
public string Name { get; set; }
public string Type { get; set; }
}
还有我的地图:
Mapper.CreateMap<Foo, Bar>()
.AfterMap((s, d) => { if (s.Code != 0) d = null; });
Mapper.CreateMap()
.AfterMap((s,d)=>{if(s.Code!=0)d=null;});
但它似乎忽略了后续地图。虽然具有所有默认属性,但已初始化条
如何使映射程序在代码不等于0的情况下返回null
谢谢一种可能的方法是-
class Converter : TypeConverter<Foo, Bar>
{
protected override Bar ConvertCore(Foo source)
{
if (source.Code != 0)
return null;
return new Bar();
}
}
static void Main(string[] args)
{
Mapper.CreateMap<Foo, Bar>()
.ConvertUsing<Converter>();
var bar = Mapper.Map<Bar>(new Foo
{
Code = 1
});
//bar == null true
}
类转换器:类型转换器
{
受保护的覆盖条(Foo源)
{
if(source.Code!=0)
返回null;
返回新条();
}
}
静态void Main(字符串[]参数)
{
Mapper.CreateMap()
.ConvertUsing();
var bar=Mapper.Map(新的Foo
{
代码=1
});
//bar==null true
}
我创建了以下扩展方法来解决这个问题
public static IMappingExpression<TSource, TDestination> PreCondition<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> mapping
, Func<TSource, bool> condition
)
where TDestination : new()
{
// This will configure the mapping to return null if the source object condition fails
mapping.ConstructUsing(
src => condition(src)
? new TDestination()
: default(TDestination)
);
// This will configure the mapping to ignore all member mappings to the null destination object
mapping.ForAllMembers(opt => opt.PreCondition(condition));
return mapping;
}
publicstaticimappingexpression前置条件(
此IMappingExpression映射
,Func条件
)
其中TDestination:new()
{
//这将配置映射以在源对象条件失败时返回null
mapping.ConstructUsing(
src=>条件(src)
?新的TDestination()
:默认值(TDestination)
);
//这将配置映射以忽略到空目标对象的所有成员映射
mapping.ForAllMembers(opt=>opt.premission(condition));
回归映射;
}
对于所讨论的情况,可以这样使用:
Mapper.CreateMap<Foo, Bar>()
.PreCondition(src => src.Code == 0);
Mapper.CreateMap()
.predition(src=>src.Code==0);
现在,如果条件失败,映射器将返回null;否则,它将返回映射对象。我更喜欢自定义值解析程序。这是我的照片
public class CustomValueResolver : IValueResolver<Foo, Bar, string>
{
public string Resolve(Foo source, Bar destination, string destMember, ResolutionContext context)
{
return source.Code != 0 ? null : "asd";
}
}
public class YourProfile : Profile
{
public YourProfile()
{
this.CreateMap<Foo, Bar>()
.ForMember(dst => dst.Name, opt => opt.MapFrom<CustomValueResolver>())
// ...
;
}
}
公共类CustomValueResolver:IValueResolver
{
公共字符串解析(Foo源、Bar目标、字符串destMember、ResolutionContext上下文)
{
返回源代码!=0?空:“asd”;
}
}
公共类YourProfile:Profile
{
公共档案()
{
这个
.FormMember(dst=>dst.Name,opt=>opt.MapFrom())
// ...
;
}
}
可能的重复我必须在TypeConverter中手动添加我想要的映射,还是我可以让它在之后自动映射?恐怕是的。因为现在您负责创建目标类型。