reverse manytoone dapper code example

Example: reverse manytoone dapper

var lookup = new Dictionary();
            var res = connection.QueryAsync(@"
                    SELECT *
                    FROM [Users] AS [u]
                    LEFT JOIN [Courses] AS [c] ON [u].[Id] = [c].[MasterId]
                    ORDER BY [u].[Id], [c].[Id]                    
                    ", (user, course) =>
                {
                    Users userObj;
                    if (!lookup.TryGetValue(user.Id, out userObj))
                    {
                        lookup.Add(user.Id, userObj = user);
                    }

                    if (userObj.MasterCourse == null)
                    {
                        userObj.MasterCourse = new List();
                    }
                    if (course != null)
                    {
                        userObj.MasterCourse.Add(course);
                    }

                    return userObj;
                },
                 splitOn: "Id"
             ).Result;



            return lookup.Values.ToList();

Tags:

Misc Example