问题描述
我已经尝试了很多,但是找不到我真正想要的东西.这是我的情况:我有一个带有导航属性和viewModel的EF-Core实体:
I´ve tried a lot, but I can´t find what I´m really looking for. This is my case: I have an EF-Core entity with navigation-properties and a viewModel:
public class SomeEntity
{
public Guid Id { get; set; }
public virtual NestedObject NestedObject { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
}
public class SomeEntityViewModel
{
public Guid Id { get; set; }
public string NestedObjectStringValue { get; set; }
public int NestedValueIntValue { get; set; }
}
这是我的CreateMap,即使没有设置NestedObject-Property,它也会创建一个新的NestedObject(条件似乎在这里并不适用):
This is my CreateMap which creates a new NestedObject even if no NestedObject-Property is set (Condition doesn´t seem to apply here):
CreateMap<SomeEntityViewModel, SomeEntity>(MemberList.Source)
.ForPath(m => m.NestedObject.StringValue, opt =>
{
opt.Condition(s => s.Destination.NestedObject != null);
opt.MapFrom(m => m.NestedObjectStringValue);
});
这避免了在属性为null的情况下避免创建新的NestedObject,但如果不为null,则不会映射NestedObject属性:
This avoids Creating a new NestedObject if Properties are null but if not, the NestedObject Properties are not mapped:
CreateMap<SomeEntityViewModel, SomeEntity>(MemberList.Source)
.ForMember(m => m.NestedObject, opt => opt.AllowNull());
第二个CreateMap如果设置了NestedObject-Properties,则不映射.如果未设置属性",则首先创建一个新的NestedObject.但是两者都不起作用.有什么想法可以解决这个问题吗?
Second CreateMap doesn´t Map NestedObject-Properties if they are set, first creates a new NestedObject if the Properties are not set. But both together are not working. Any ideas how to solve this?
推荐答案
删除 ReverseMap()
,然后尝试使用AutoMapper 条件映射并使用 ForPath
而不是 ForMember
来嵌套子对象属性:
Remove ReverseMap()
,then try to use AutoMapper Conditional Mapping and use ForPath
instead of ForMember
for nested child object properties:
CreateMap<SomeEntityViewModel, SomeEntity>()
.ForPath(
m => m.NestedObject.StringValue,
opt => {
opt.Condition(
s => s.DestinationMember != null && s.DestinationMember != ""
);
opt.MapFrom(s => s.NestedObjectStringValue);
}
);
与 IntValue
相同.
更新
因此,如果 NestedObject
为null,则您不想将 SomeEntityViewModel
中的值映射到它.如果 NestedObject
不为null,则映射有效.
So, if the NestedObject
is null, you do not want to to map the value from SomeEntityViewModel
to it. If the NestedObject
is not null,mapping works.
请参考以下使用 AfterMap
CreateMap<SomeEntityViewModel, SomeEntity>()
.ForMember(q => q.NestedObject, option => option.Ignore())
.AfterMap((src, dst) => {
if(dst.NestedObject != null)
{
dst.NestedObject.StringValue = src.NestedObjectStringValue;
}
});
这篇关于如果object为null,如何配置Automapper 9以忽略Object-Properties,如果不为null,则如何映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!