C# 使用自动映射器映射对象
我的课程如下所示:C# 使用自动映射器映射对象,c#,automapper,C#,Automapper,我的课程如下所示: public class Student{ public string Name { get; set; } public string Id { get; set; } public List<Course> Courses { get; set; } public string Address { get; set; } } public class Course{ public string Id { get; se
public class Student{
public string Name { get; set; }
public string Id { get; set; }
public List<Course> Courses { get; set; }
public string Address { get; set; }
}
public class Course{
public string Id { get; set; }
public string Description { get; set; }
public Date Hour { get; set; }
}
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Student, StudentProperties>();
cfg.CreateMap<Student, StudentModel>();
});
其中StudentProperties是学生类的其余属性
public class StudentProperties{
public string Name { get; set; }
public List<Course> Courses { get; set; }
public string Address { get; set; }
}
公共类StudentProperties{
公共字符串名称{get;set;}
公共列表课程{get;set;}
公共字符串地址{get;set;}
}
根据AutoMapper文档(),我们可以在执行映射时使用自定义解析器来解析目标成员。
但我不想为解析器添加新类
我想知道是否有一种执行映射的简单方法,只需执行以下简单配置:
public class Student{
public string Name { get; set; }
public string Id { get; set; }
public List<Course> Courses { get; set; }
public string Address { get; set; }
}
public class Course{
public string Id { get; set; }
public string Description { get; set; }
public Date Hour { get; set; }
}
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Student, StudentProperties>();
cfg.CreateMap<Student, StudentModel>();
});
Mapper.Initialize(cfg=>
{
CreateMap();
CreateMap();
});
cfg.CreateMap()
福门博先生(
x=>x.属性,
x=>x.ResolveUsing((src)=>{
返回新的StudentProperties(){
Name=src.Name,
课程=src.课程,
地址=src.地址
}));
我想你可以试着做类似的事情
CreateMap<Student, StudentModel>()
.ForMember(dist => dist.Properties,
opt => opt.MapFrom(src => Mapper.Map<StudentProperties>(src)))
CreateMap()
.FormMember(dist=>dist.Properties,
opt=>opt.MapFrom(src=>Mapper.Map(src)))
这里有一个选项适合您,可以对StudentModel
和StudentProperties使用AutoMapper
:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Student, StudentProperties>();
cfg.CreateMap<Student, StudentModel>()
.ForMember(dest => dest.Properties,
opt => opt.ResolveUsing(Mapper.Map<StudentProperties>));
});
Mapper.Initialize(cfg=>
{
CreateMap();
cfg.CreateMap()
.ForMember(dest=>dest.Properties,
opt=>opt.resolvesusing(Mapper.Map));
});
在这里,我们使用的是ResolveUsing
,但使用的是Func
版本,以避免创建新类。这个Func
只是Mapper.Map
本身,它已经知道如何从Student
映射到StudentProperties
,谢谢。但是如果我有一个属性呢:public Employee Teacher{get;set;}
在StudentModel类中,我想将它与StudentModel类中的另一个属性public EmployeeModel TeacherProperties{get;set;}
进行映射?我最后通过添加以下代码.ForMember,找到了上述问题的解决方案(dest=>dest.TeacherProperties,opt=>opt.MapFrom(src=>src.Teacher));
在configcfg.CreateMap()
下。但是我不知道是否有更好的方法。这可以工作,但我不想对每个属性进行映射属性。