经常会有对象属性互相赋值的操作,但是频繁的写实在是搬运工一样,比较难受比如下面两个类
public class AgencyBdm
{
public new int Id { set; get; }
public string AgencyId { set; get; }
public string AgencyName { set; get; }
public string Region { set; get; }
public string Bdm { set; get; }
public string BdmEmail { set; get; }
public string Dosm { set; get; }
public string DosmEmail { set; get; }
public DateTime CreateDate { get; set; }
public string Modifier { get; set; }
public string Creator { get; set; }
public DateTime? UpdateDate { get; set; }
public List<string> Errors { get; set; } = new List<string>();
public int RowNumber { get; set; }
}
public class AgencyContactModel
{
public string AGENCYID { get; set; }
public string AGENCY_NAME { get; set; }
public string REGION { get; set; }
public string BDM { get; set; }
public string BDM_EMAIL { get; set; }
public string DOSM { set; get; }
public string DOSM_EMAIL { set; get; }
public DateTime CreateDate { set; get; }
}
他需要一个个的赋值操作
var model = new AgencyContactModel();
var dbModel = new AgencyBdm {
....此次赋值省略
}
model.Id = dbModel.Id;
model.AGENCYID = dbModel.AgencyId;
model.AGENCY_NAME = dbModel.AgencyName;
model.REGION = dbModel.Region;
model.BDM = dbModel.Bdm;
model.BDM_EMAIL = dbModel.BdmEmail;
model.DOSM = dbModel.Dosm;
model.DOSM_EMAIL = dbModel.DosmEmail;
然而这还不够,我们经常还需要反向操作赋值
dbModel.AgencyId = model.AGENCYID;
这样的体力活着实让人乏累,也许很多人说可以用AutoMapper,但是AutoMapper 仍然不能让我感到满意,AutoMapper 的代码我就不写了,我们使用Mapster,个人觉得很轻巧,很好用。下面以一个在 Asp.net MVC 的Controller 为例,去设置两个对象属性的双向映射关系
public class SellOutPlanController : Controller
{
// 之所以用静态构造函数是因为只会执行一次,TypeAdapterConfig 执行多次时候报错的
static SellOutPlanController()
{
// 设置对象的双向映射,TwoWays就表示双向映射
TypeAdapterConfig<AgencyBdm, AgencyContactModel>
.NewConfig()
.TwoWays()
.Map(dto => dto.Id, poco => poco.Id)
.Map(dto => dto.AGENCYID, poco => poco.AgencyId)
.Map(dto => dto.AGENCY_NAME, poco => poco.AgencyName)
.Map(dto => dto.REGION, poco => poco.Region)
.Map(dto => dto.BDM, poco => poco.Bdm)
.Map(dto => dto.BDM_EMAIL, poco => poco.BdmEmail)
.Map(dto => dto.DOSM, poco => poco.Dosm)
.Map(dto => dto.DOSM_EMAIL, poco => poco.DosmEmail)
.Map(dto => dto.CreateDate, poco => poco.CreateDate);
}
// 然后我们到 Action 下面来使用咯,把 AgencyContactModel 拷贝到 AgencyContactModel 对象
public ActionResult ModelSwitch1()
{
var model = new AgencyContactModel();
var dbModel = new AgencyBdm {
...此处赋值省略
}
model = dbModel.Adapt<AgencyContactModel>();
... 返回结果省略
}
// 然后下面的倒过来,把 AgencyContactModel 拷贝到 AgencyContactModel
public ActionResult ModelSwitch2()
{
var dbModel = new AgencyBdm();
var model = new AgencyContactModel{
...此处赋值省略
}
dbModel = model .Adapt<AgencyBdm>();
... 返回结果省略
}
}
可以看到,无论是对象A拷贝到对象B,还是对象B拷贝到对象A,只用配置一次就可以了,跟AutoMapper 的代码量我就不去对比,反正用过的都说香,再也不想用AutoMapper了,唯一一点就是这个库的知名度还赶不上AutoMapper