【发布时间】: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