C# 从DTO映射到实体时,停止自动映射在虚拟属性上创建空对象

C# 从DTO映射到实体时,停止自动映射在虚拟属性上创建空对象,c#,automapper,C#,Automapper,我已经设置了Automapper配置,当从实体映射到DTO时就可以了。但是,当我尝试从Dto映射回实体时,它会用空数据填充实体的所有虚拟属性,从而创建新对象 应演示问题的Psuedocode: public class MyEntity { public string MyString { get; set; } public virtual MyOtherEntity MyOtherEntity } public class MyEntityDto { public

我已经设置了Automapper配置,当从实体映射到DTO时就可以了。但是,当我尝试从Dto映射回实体时,它会用空数据填充实体的所有虚拟属性,从而创建新对象

应演示问题的Psuedocode:

public class MyEntity
{
    public string MyString { get; set; }

    public virtual MyOtherEntity MyOtherEntity
}

public class MyEntityDto
{
    public string MyString { get; set; }

    public virtual MyOtherEntityDto MyOtherEntity
}

config.CreateMap<MyEntity, MyEntityDto>()
    .ForSourceMember(obs => obs.MyOtherEntity, dto => dto.DoNotValidate())
    .ReverseMap();


// using this to create an Entity creates an empty MyOtherEntity object on it
var entity = Mapper.Map<MyEntityDto, MyEntity>(myEntityDto);
_context.MyEntities.Add(entity);

// so this tries to create a new MyOtherEntity in the db
_context.SaveChanges();
公共类MyEntity
{
公共字符串MyString{get;set;}
公共虚拟myotherity myotherity
}
公共类MyEntityDto
{
公共字符串MyString{get;set;}
公共虚拟MyThere实体到MyThere实体
}
config.CreateMap()
.ForSourceMember(obs=>obs.MyOtherEntity,dto=>dto.DoNotValidate())
.ReverseMap();
//使用此选项创建实体将在其上创建一个空MyOtherEntity对象
var entity=Mapper.Map(myEntityDto);
_context.myenties.Add(实体);
//因此,这试图在db中创建一个新的Myotherity
_SaveChanges();
我可以通过手动创建实体来解决这个问题,但是没有办法设置Automapper使这些属性为空吗?

对于ReverseMap(),Automapper创建了一个反向映射配置,其中包括取消平台化,从而为虚拟属性创建新对象。 您可以删除对ReverseMap()的调用并创建两个单独的映射,或者使用Ignore


configuration.AllowNullDestinationValues=true@LucianBargaoanu谢谢-你能在单个映射上设置吗?不,只是全局或每个配置文件。但在10.0中,情况发生了变化: