Multi-Mapper en Dapper, una a muchas relaciones

asp.net-mvc c# dapper dapper-extensions

Pregunta

Estoy tratando de obtener el valor de mi base de datos con una relación de uno a muchos tengo mi objeto como este

Estudiante

[Table("Student")]
    public class Student  : IStudent
    {    

        public int Id { get; set; }
        public string Lastname { get; set; }
        public string FirstMidName { get; set; }
        public DateTime? EnrollmentDate { get; set; }

        [Write(false)]
        public IEnumerable<Enrollment> Enrollments { get; set; }
    }

Inscripción

[Table("Enrollment")]
    public class Enrollment
    {
        public int Id { get; set; }
        public int CourseId { get; set; }
        public int StudentId { get; set; }
        public string Grade { get; set; }
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }

Curso

[Table("Course")]
public class Course
{   
    public int Id { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    public virtual IEnumerable<Enrollment> Enrollments { get; set; }
}

Aquí está mi código apuesto

_connection = Connect.GetOpenConnection();
        const string query = @"SELECT * FROM Student stu where id = @id " +
                             "SELECT * FROM Enrollment enr WHERE enr.StudentId in (SELECT id FROM Student stu where id = @id) " +
                             "SELECT * FROM Course cou WHERE cou.Id in (SELECT CourseId from Enrollment where StudentId = @id)";

        var result = _connection.QueryMultiple(query, new { id = id })
            .Map<Student, Enrollment, Course, int>(
                student => student.Id,     
                enrollment => enrollment.StudentId,
                course=>course.Id,
                (student, enrollments) => student.Enrollments = enrollments ,
                (student, courses) => student.Enrollments.ForEach(s=>courses.ForEach(x=>s.Course.Title = x.Title) )
            ).FirstOrDefault();

según la instrucción Aquí todo lo que tengo que hacer es ampliar la jerarquía de 3 niveles, pero no puedo hacerlo funcionar

aquí está mi GridReader con mapper

public static IEnumerable<TFirst> Map<TFirst, TSecond, TThird, TKey>
        (
        this SqlMapper.GridReader reader,
        Func<TFirst, TKey> firstKey,
        Func<TSecond, TKey> secondKey,
        Func<TThird, TKey> thirdKey,
        Action<TFirst, IEnumerable<TSecond>> addSecond,
        Action<TFirst, IEnumerable<TThird>> addThird
        )
    {
        var result = reader.Read<TFirst>().ToList();

        var secondMap = reader
            .Read<TSecond>()
            .GroupBy(s=>secondKey(s))
            .ToDictionary(g => g.Key, g => g.AsEnumerable());

        var thirdMap = reader
           .Read<TThird>()
           .GroupBy(t => thirdKey(t))
           .ToDictionary(g => g.Key, g => g.AsEnumerable());     


        foreach (var item in result)
        {
            IEnumerable<TThird> third;
            if (thirdMap.TryGetValue(firstKey(item), out third))
            {
                addThird(item, third);
            }

            IEnumerable<TSecond> second;
            if (secondMap.TryGetValue(firstKey(item), out second))
            {
                addSecond(item, second);
            }

        }



        return result.ToList();
    }

cuando ejecuto mi aplicación aquí aparece el resultado con el ID de 1 notificación de que el título del curso no tiene ningún valor. Espero que me puedas ayudar, gracias. ha fallado

ACTUALIZACIÓN 1

Noté que obtengo el valor nulo aquí, no entra dentro de la declaración if

IEnumerable<TSecond> second;
        if (secondMap.TryGetValue(firstKey(item), out second))
        {
            addSecond(item, second);
        }

ACTUALIZACIÓN 2

Resuelvo el problema aquí es lo que hago

var ctr = 0;
        var mapped2 = conn.QueryMultiple(query, new {id})
            .Map<Student, Enrollment, Course, int>(
                student => student.StudentId,
                enrollment => ctr = enrollment.StudentId,
                course=>course.CourseId = ctr,
                ((student, enrollments) => { student.Enrollments = enrollments; }),
                ((student, courses) => courses.ToList().ForEach(s=> student.Enrollments.ToList().ForEach(x=>x.Course = new Course
                {
                    Title = s.Title
                }))));

observe que agregué ctr para obtener el valor de CourseId en la enrollment => ctr = enrollment.StudentId . Ok ahora me enfrento a otro problema, cómo obtener el valor de los courses aquí es mi código

((student, courses) => courses.ToList (). ForEach (s => student.Enrollments.ToList (). ForEach (x => x.Course = new Course {Title = s.Title}))

solo estoy obteniendo el último valor

Respuesta aceptada

Así es como resuelvo mi problema

Como los detalles de UPDATE 2 anteriores agregué una variable ctr para obtener el valor de CourseId de la Enrollment y pasar a Course para obtener el valor correcto. Después de eso me enfrento a otro problema sobre cómo pasar el valor de Course de Student.Enrollment.Course de Student.Enrollment.Course Aquí es cómo lo Student.Enrollment.Course .

var enrollLst = new List<Enrollment>(); una variable var enrollLst = new List<Enrollment>(); para mantener el valor de Enrollment desde la primera acción

((student, enrollments) =>
                {
                    enrollLst = enrollments.ToList();
                }),

Segunda acción

((student, courses) =>
                {
                    var ctrId = 0;  
                    courses.ToList().ForEach(cour =>
                    {
                        if (cour != null)
                        {
                            enrollLst[ctrId].Course = cour;
                            ctrId++;
                        }
                        else
                        {
                            enrollLst[ctrId].Course = null;
                            ctrId++;
                        }   
                    });
                    student.Enrollments = enrollLst;
                })).FirstOrDefault(); 

a continuación está mi código completo

_connection = Connect.GetOpenConnection();
        const string query = "SELECT * from Student stu where StudentId = @id  " +
                             "SELECT * from Enrollment enr where enr.StudentId in ( SELECT StudentId from Student stu where Studentid = @id)  " +
                             "SELECT * FROM Course cou WHERE cou.CourseId in (SELECT CourseId from Enrollment where StudentId = @id)";

        var enrollLst = new List<Enrollment>();
        var ctr = 0;
        var result = _connection.QueryMultiple(query, new { id })
            .Map<Student, Enrollment, Course, int>(
                student => student.StudentId,
                enrollment => ctr = enrollment.StudentId,
                course => course.CourseId = ctr,
                ((student, enrollments) =>
                {
                    enrollLst = enrollments.ToList();
                }),
                ((student, courses) =>
                {
                    var ctrId = 0;  
                    courses.ToList().ForEach(cour =>
                    {
                        if (cour != null)
                        {
                            enrollLst[ctrId].Course = cour;
                            ctrId++;
                        }
                        else
                        {
                            enrollLst[ctrId].Course = null;
                            ctrId++;
                        }   
                    });
                    student.Enrollments = enrollLst;
                })).FirstOrDefault(); 

GridReader con mapper extendido con jerarquía de 3 niveles como se indica aquí

public static IEnumerable<TFirst> Map<TFirst, TSecond, TThird, TKey>
        (
        this SqlMapper.GridReader reader,
        Func<TFirst, TKey> firstKey,
        Func<TSecond, TKey> secondKey,
        Func<TThird, TKey> thirdKey,
        Action<TFirst, IEnumerable<TSecond>> addSecond,
        Action<TFirst, IEnumerable<TThird>> addThird
        )
    {
        var result = reader.Read<TFirst>().ToList();

        var secondMap = reader
            .Read<TSecond>()
            .GroupBy(secondKey)
            .ToDictionary(g => g.Key, g => g.AsEnumerable());

        var thirdMap = reader
           .Read<TThird>()
           .GroupBy(thirdKey)
           .ToDictionary(g => g.Key, g => g.AsEnumerable());     

        foreach (var item in result)
        {
            IEnumerable<TSecond> second;
            if (secondMap.TryGetValue(firstKey(item), out second))
            {
                addSecond(item, second);
            }

            IEnumerable<TThird> third;
            if (thirdMap.TryGetValue(firstKey(item), out third))
            {
                addThird(item, third);
            }  
        }  
        return result.ToList();
    }


Licencia bajo: CC-BY-SA with attribution
No afiliado con Stack Overflow
¿Es esto KB legal? Sí, aprende por qué
Licencia bajo: CC-BY-SA with attribution
No afiliado con Stack Overflow
¿Es esto KB legal? Sí, aprende por qué