簡體   English   中英

從 DTO 映射到實體時,停止 Automapper 在虛擬屬性上創建空對象

[英]Stop Automapper creating empty objects on virtual properties when mapping from DTO to Entity

我已經設置了我的 Automapper 配置,從實體映射到 Dtos 時很好。 但是,當我嘗試從 Dto 映射回實體時,它會用空數據填充實體的所有虛擬屬性,從而導致創建新對象。

應該證明問題的偽代碼:

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();

我可以通過手動創建實體來解決這個問題,但是沒有辦法設置 Automapper 以將這些屬性留空嗎?

對於 ReverseMap() AutoMapper 創建一個反向映射配置,其中包括unflattening ,這導致為虛擬財產創建新對象。 您可以刪除對 ReverseMap() 的調用並創建兩個單獨的地圖,或者您可以使用 Ignore。

https://docs.automapper.org/en/stable/Reverse-Mapping-and-Unflattening.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM