【问题标题】:AutoMapper, Don't Overwrite Existing Value if Not PresentAutoMapper,如果不存在则不要覆盖现有值
【发布时间】:2019-07-31 04:23:29
【问题描述】:

我有两个相似但不完全相同的模型

public class ResponseModel
{
    public int? AccountId { get; set; }
    public string AccountNumber { get; set; }
    public string AccountLegalname { get; set; }
    public string Link { get; set; }
}

public class Information
{
    public int? IdentityId { get; set; }
    public int? AccountId { get; set; }
    public string AccountNumber { get; set; }
    public string AccountLegalName { get; set; }
}

我正在尝试像这样结合这两个模型

var test1 = new Information(){
    IdentityId = 1234
};

var test2 = new ResponseModel()
{
    AccountId = 123214,
    AccountLegalname = "test",
    AccountNumber = "9239235",
    Link = "link"
};

test1 = _mapper.Map<ResponseModel, Information>(test2);

我想要的是这导致 test1 结合两个模型值来填充 Information 的一个完整实例。

但实际发生的是来自 test2 的所有信息都插入到 test1 和 test1.IdentityId = null

我试过了,

this.CreateMap<ResponseModel, Information>()
    .ForAllMembers(o => o.Condition((source, destination, member) => member != null));

但没有运气。

我怎样才能使 test2 不会覆盖存在于 int test1 而不是 test2 的数据?

【问题讨论】:

  • 我记得曾经做过类似的事情,并且必须为每个成员设置条件。
  • 我认为 Obeds 的答案在底部有效:stackoverflow.com/questions/12262940/…
  • 这里的问题不是你覆盖了属性,问题是你使用的重载构造了一个新的目标对象,test1中的实例从未被使用,而是你覆盖了@987654329 @ 使用这个新实例,丢失您分配给该 Id 属性的原始实例。

标签: c# automapper


【解决方案1】:

如果我没记错的话,您可以将目标作为参数传递,以通过重载调用该特定功能:

test1 = _mapper.Map(test2, test1 );

【讨论】:

  • 而且我认为你也可以不用类型,它们是从参数中推断出来的。
  • 是的,就是这样。打得好
  • 让我想知道它将如何处理值类型,例如 ints。
猜你喜欢
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 2022-08-02
  • 2011-09-15
  • 1970-01-01
  • 2020-06-06
相关资源
最近更新 更多