我在使用.Ignore()
时遇到麻烦。
我有一个Employee
实体,在Employee
实体中,我有List_TaskEntity
,在List_TaskEntity
内部,我有List_TaskUserEntity
。我还具有所有实体的DTO模型。
我无法做的是:我不想允许客户通过List_TaskUserEntity
编辑EmployeeModel
,
因此在映射中,我想这样忽略List_TaskUser
;
cfg.CreateMap<TaskModel, TaskEntity>().ForMember(z => z.Users, opt => opt.Ignore()); //doesnt work,
cfg.CreateMap<TaskModel, TaskEntity>().ForMember(z => z.Users, opt => opt.UseDestinationValue()); //doesnt work
所需结果; 无论我是否在Employee模型中编辑用户集合,映射后都应始终为我带来未修改的用户实体列表。
非常感谢。
public class EmployeeEntity
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<TaskEntity> Tasks { get; set; }
}
public class EmployeeModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<int> Salary { get; set; }
public List<TaskModel> Tasks { get; set; }
}
public class TaskModel
{
public int TaskId { get; set; }
public string Name { get; set; }
public ICollection<TaskUserModel> Users { get; set; }
}
public class TaskUserModel
{
public int TaskId { get; set; }
public int UserId { get; set; }
}
public class TaskEntity
{
public int TaskId { get; set; }
public string Name { get; set; }
public ICollection<TaskUserEntity> Users { get; set; }
}
public class TaskUserEntity
{
public int TaskId { get; set; }
public int UserId { get; set; }
}
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<EmployeeEntity, EmployeeModel>();
cfg.CreateMap<EmployeeModel, EmployeeEntity>();
cfg.CreateMap<TaskEntity, TaskModel>();
cfg.CreateMap<TaskModel, TaskEntity>().ForMember(z => z.Users, opt => opt.Ignore());
cfg.CreateMap<TaskUserEntity, TaskUserModel>();
cfg.CreateMap<TaskUserModel, TaskUserEntity>();
});
var entity = new EmployeeEntity()
{
Id = 1,
Age = 5,
Name = "Joseph",
Tasks = new List<TaskEntity>() {
new TaskEntity()
{
Name="X",
TaskId=1,
Users=new List<TaskUserEntity>() { new TaskUserEntity() {TaskId=1,UserId=2 } }
}
}
};
var model = new EmployeeModel()
{
Id = 1,
Age = 5,
Name = null,
Tasks = new List<TaskModel>() {
new TaskModel()
{
Name="X",
TaskId=1,
Users=null // In model i am making it null, but it should brng me taskusers list anyhow.
} }
};
var mapper = config.CreateMapper();
var updatedEntity = mapper.Map(model, entity);
}
}