[英]AutoMapper to force null
I use Automapper with EntityFramework Core, and have the following configuration for one of my objects ( Couche
, having associated an Affaire
and a Sol
object)我将 Automapper 与 EntityFramework Core 一起使用,并为我的一个对象(
Couche
,关联了Affaire
和Sol
对象)进行了以下配置
CreateMap<Couche, CoucheDTO>()
.ForMember(dto => dto.AffaireId, o => o.MapFrom(p => p.Affaire.Id))
.ForMember(dto => dto.SolId, o => o.MapFrom(p => p.Sol.Id))
.ForMember(dto => dto.SolNom, o => o.MapFrom(p => p.Sol.Nom))
.ForMember(dto => dto.SolCode, o => o.MapFrom(p => p.Sol.Code))
.ReverseMap()
.ForPath(couche => couche.Affaire, o => o.MapFrom(p => {return null; })) // ???
.ForPath(couche => couche.Sol, o => o.Ignore()); // ???
When I reverse map (from DTO to Business Object), I need only the correct AffaireId
, the Affaire
field should be set to null (I don't need to create invalid half-filled objects).当我反转 map (从 DTO 到业务对象)时,我只需要正确的
AffaireId
, Affaire
字段应设置为 null (我不需要创建无效的半填充对象)。 How to do it with reverse map?反向 map 怎么办?
Ignore
seem do not put null.... Ignore
好像不要放null....
PS. PS。 I tried
我试过了
.ForPath(couche => couche.Affaire, o => o.MapFrom<AffaireDTO>(p => null))
.ForPath(couche => couche.Sol, o => o.MapFrom<AffaireDTO>(p => null));
but get then但到那时
InvalidOperationException: No coercion operator is defined between types 'MyApp.Core.Entities.Sol' and 'MyApp.Core.Entities.Affaire'.
InvalidOperationException:在类型“MyApp.Core.Entities.Sol”和“MyApp.Core.Entities.Affaire”之间未定义强制运算符。 System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)
System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType,表达式表达式,类型 convertToType)
DependencyResolutionException: An exception was thrown while activating MyApp.Web.Services.SondageService -> λ:AutoMapper.IMapper -> λ:AutoMapper.IConfigurationProvider.
DependencyResolutionException:激活 MyApp.Web.Services.SondageService -> λ:AutoMapper.IMapper -> λ:AutoMapper.IConfigurationProvider 时引发异常。 Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action next)
Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action next)
There should be no need to use 'return'.应该没有必要使用'return'。
Try .ForPath(couche => couche.Affaire, o => o.MapFrom(p => null))
尝试
.ForPath(couche => couche.Affaire, o => o.MapFrom(p => null))
Finally, found solution to infere the type... (Affaire)null
:最后,找到了推断类型的解决方案...
(Affaire)null
:
.ForPath(couche => couche.Affaire, o => o.MapFrom(p => (Affaire)null))
.ForPath(couche => couche.Sol, o => o.MapFrom(p => (Sol)null));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.