我在映射相互引用的嵌套类时遇到问题。实体框架在循环中存在嵌套实体,因此我最终在映射后嵌套在嵌套子实体中。
我做了一个示例程序,你可以复制粘贴,显示问题。在我的实际程序中,我正在映射集合,因此需要循环遍历整个集合以将所有嵌套对象设置为null并且感觉不整洁,我宁愿调整我的映射规则(如果可能)。
以下是显示问题的代码:
using AutoMapper;
public class Job
{
public string Name { get; set; }
public PayPackage PayPackage { get; set; }
}
public class PayPackage
{
public string Name { get; set; }
public Job Job { get; set; }
}
public class JobViewModel
{
public string Name { get; set; }
public PayPackageViewModel PayPackage { get; set; }
}
public class PayPackageViewModel
{
public string Name { get; set; }
public JobViewModel Job { get; set; }
}
class Program
{
static void Main(string[] args)
{
var job = new Job
{
Name = "Job Name",
PayPackage = new PayPackage
{
Name = "Pay Package Name"
}
};
job.PayPackage.Job = job; //simulate how EF is populating entity
var config = new MapperConfiguration(c =>
{
c.CreateMap<Job, JobViewModel>();
c.CreateMap<JobViewModel, Job>();
c.CreateMap<PayPackage, PayPackageViewModel>();
c.CreateMap<PayPackageViewModel, PayPackage>();
});
var mapper = config.CreateMapper();
var jobVm = mapper.Map<JobViewModel>(job);
Assert.IsTrue(jobVm.PayPackage != null);
Assert.IsTrue(jobVm.PayPackage.Job == null); //how do I specify mapping so this passes?
}
}
避免父对象在映射结果中出现两次的最佳方法是什么?
EG
c.CreateMap<Job, JobViewModel>()
.ForMember(dest => dest.PayPackage, opt => opt.Ignore());
映射发生时,将忽略目标PayPackage
对象的JobViewModel
属性。