AutoMapper 能否被“ 说服” 暂停特定绘图?
为了说明要完成的工作,我将用一个插图来说明。假设我有一个存储库, < 坚固的> 学生存储库 , 使用 LINQ 与数据库对象(表)如学生、课程、活动、俱乐部等进行互动。 在应用程序方面,有匹配的域目标学生、课程、活动、俱乐部。 学生类包括类型课程、活动和俱乐部的阵列成员, 例如:
public class Student
{
// ... more members
public Course[] Courses { get; set; }
public Activity[] Activities { get; set; }
public Club[] Clubs { get; set; }
// ... even more members
}
自动Mapper 被配置为将数据库对象映射到域对象的图象, 以在学生仓库的静态构建器中定义映射 :
public class StudentRepository : IStudentRepository
{
static class StudentRepository
{
// ... other mappings
Mapper.CreateMap<TableStudent, Student>()
.ForMember(dest => dest.Courses, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Course>>(src.TableCourses)))
.ForMember(dest => dest.Activities, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Activity>>(src.TableActivities)))
.ForMember(dest => dest.Clubs, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Clubs>>(src.TableClubs)))
// where TableStudents, TableCourses, TableActivities, TableClubs are database entities
// ... yet more mappings
}
}
“ persude” Automapp 能否在一个函数块内暂停映射? 例如 :
public Student[] GetStudents()
{
DataContext dbContext = new StudentDBContext();
var query = dbContext.Students;
// => SUSPEND CONFIGURATION MAPPINGS for Subjects, Activities and Clubs WHILE STILL making use of others
// => The idea here it to take personal charge of manually setting the particular members (*for some specific reasons)
var students = Mapper.Map<Student>(query); // => Still be able to use AutoMapper to map other members
}
public Student[] OtherStudentRepositoryMethods()
{
// Other repository methods continue to make use of the mappings configured in the static constructor
}
注意 "为某些具体原因 < 坚固> < / 坚固> : 人们可能想要从AutoMapper手中夺去控制权的原因之一是 < a href="http://codebbetter.com/davidhayden/2007/08/06/linq-to-sql-query-rapt-sql-sql-querios-to-breat-down-in-advanced-scenarios/ < a > 。 在 1 :n 社团中, LINQ 到 SQL 只支持加入 1:n 连接查询 < / strong > 。 AutoMapper在这里效率不高 - 向N 学生发出加载课程的呼声, 同一学生返回了装载活动的呼声, 并可能向同一学生返回的装载俱乐部发出更多呼声。