问题描述
我尝试了很多,但找不到我真正要找的东西.这是我的情况:我有一个带有导航属性和视图模型的 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);
});
如果属性为空,则避免创建新的 NestedObject,但如果不是,则不会映射 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,如果未设置 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
为空,您不想将 SomeEntityViewModel
中的值映射到它.如果 NestedObject
不为空,则映射有效.
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;
}
});
这篇关于如果对象为空,如何将 Automapper 9 配置为忽略对象属性,但如果不为空则映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!