Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

automapper - How to map DTO object to entity when some properties are missing in the DTO?

I am receiving PostDTO object in the controller and I am mapping it to Post entity and updating database. The problem occurs because PostDTO doesn't have Status property and Post entity does have Status property, so when I map PostDTO to Post, Post.Status becomes null. I don't want it to be null, I want it to stay unaffected in database. I could retrieve post from database and manually map Status property but is there better solution for this?

    public class PostDTO
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public bool Urgent { get; set; }
}
public class Post
{
    public long Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public bool Urgent { get; set; }
    public string Status { get; set; }
}

  var post = _mapper.Map<Post>(postDto); //here post.Status becomes null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could either use an approach like this to ensure the field isn't updated: https://stackoverflow.com/a/10271910/84206

OR you can first GET the entity from the database, so that the Status is populated from the database, then apply the DTO changes to the entity.

There's other approaches, but they can't really be applied with EF.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...