【问题标题】:How to map DTO object to entity when some properties are missing in the DTO?当 DTO 中缺少某些属性时,如何将 DTO 对象映射到实体?
【发布时间】:2021-01-11 15:54:11
【问题描述】:

我在控制器中接收 PostDTO 对象,并将其映射到 Post 实体并更新数据库。出现问题是因为 PostDTO 没有 Status 属性,而 Post 实体确实具有 Status 属性,所以当我将 PostDTO 映射到 Post 时,Post.Status 变为 null。我不希望它为空,我希望它在数据库中不受影响。我可以从数据库中检索帖子并手动映射 Status 属性,但有更好的解决方案吗?

    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

【问题讨论】:

    标签: entity-framework automapper dto


    【解决方案1】:

    您可以使用这样的方法来确保字段不更新: https://stackoverflow.com/a/10271910/84206

    或者您可以先从数据库中获取实体,以便从数据库中填充状态,然后将 DTO 更改应用于实体。

    还有其他方法,但它们不能真正应用于 EF。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2011-01-05
      • 1970-01-01
      • 2017-09-17
      • 2019-08-18
      相关资源
      最近更新 更多