可以“说服” AutoMapper 暂时暂停特定的映射吗?
为了说明要完成的工作,我将使用一个插图。假设我有一个存储库StudentRepository,它使用 LINQ 与数据库对象(表)进行交互,例如学生、课程、活动、俱乐部等。在应用程序端,有匹配的域对象学生、课程、活动、俱乐部。Student 类包含 Course、Activity 和 Club 类型的数组成员,例如:
public class Student
{
// ... more members
public Course[] Courses { get; set; }
public Activity[] Activities { get; set; }
public Club[] Clubs { get; set; }
// ... even more members
}
AutoMapper 配置为将数据库对象映射到在 StudentRepository 的静态构造函数中定义映射的域对象,例如:
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
}
}
是否可以“说服” AutoMapper 暂停一个功能块内的映射?例如:
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 中控制权的一个原因是http://codebetter.com/davidhayden/2007/08/06/linq-to-sql-query-tuning-appears- to-break-down-in-more-advanced-scenarios/在1:n 关联的情况下,LINQ to SQL 仅支持每个查询加入一个 1:n 关联。AutoMapper 在这里效率低下 - 为返回的 N 名学生调用 N 次加载课程,为返回的相同 N 名学生再次调用 N 次加载活动,并且可能为返回的相同 N 名学生再次调用 N 次加载俱乐部。